diff --git a/.gitattributes b/.gitattributes index 5ebde95f07643..c077807abed14 100644 --- a/.gitattributes +++ b/.gitattributes @@ -18,6 +18,7 @@ *.deb binary *.zip binary *.pdf binary +*.wav binary # These should also not be modified by git. tests/basics/string_cr_conversion.py -text diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000..65f61ebb5fad5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,54 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: 'bug' +assignees: '' + +--- + + + +**Firmware** + + + +```python +Adafruit CircuitPython 6.2.0-beta.2 on 2021-03-01; Raspberry Pi Pico with rp2040 +``` + +**Code/REPL** + + + +```python +import busio, bitbangio +i2c = bitbangio.I2C(board.GP1, board.GP0) +``` + +**Behavior** + + + +```python +Traceback (most recent call last): + File "", line 1, in +TimeoutError: Clock stretch too long +``` + +**Description** + + + +- Error while using i2c... +- Only happens when... +- might be related to #4291... + +**Additional Info** + + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000..73bf24af0ca68 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,7 @@ +contact_links: + - name: Adafruit Forum + url: https://forums.adafruit.com/ + about: Official Adafruit technical support forum. Good for getting help on getting a project working. + - name: Adafruit Discord + url: https://adafru.it/discord + about: Unofficial chat with many helpful folks and normally prompt replies. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000..4f65b84145f7e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,11 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: 'enhancement' +assignees: '' + +--- + + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 34e0b082174c6..cb65a9cd635ea 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -38,13 +38,11 @@ jobs: sudo apt-get update sudo apt-get install -y eatmydata sudo eatmydata apt-get install -y gettext librsvg2-bin mingw-w64 latexmk texlive-fonts-recommended texlive-latex-recommended texlive-latex-extra - pip install requests sh click setuptools cpp-coveralls "Sphinx<4" sphinx-rtd-theme recommonmark sphinx-autoapi sphinxcontrib-svg2pdfconverter polib pyyaml astroid isort black awscli mypy + pip install -r requirements-dev.txt - name: Versions run: | gcc --version python3 --version - - name: Translations - run: make check-translate - name: New boards check run: python3 -u ci_new_boards_check.py working-directory: tools @@ -81,6 +79,7 @@ jobs: working-directory: tests - name: Print failure info run: | + shopt -s nullglob; for exp in *.exp; do testbase=$(basename $exp .exp); echo -e "\nFAILURE $testbase"; @@ -133,15 +132,6 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - name: Install dependencies - run: | - brew install gettext - echo >>$GITHUB_PATH /usr/local/opt/gettext/bin - - name: Versions - run: | - gcc --version - python3 --version - msgfmt --version - uses: actions/checkout@v2.2.0 with: submodules: true @@ -151,6 +141,15 @@ jobs: run: | git describe --dirty --tags echo >>$GITHUB_ENV CP_VERSION=$(git describe --dirty --tags) + - name: Install dependencies + run: | + brew install gettext + echo >>$GITHUB_PATH /usr/local/opt/gettext/bin + - name: Versions + run: | + gcc --version + python3 --version + msgfmt --version - name: Build mpy-cross run: make -C mpy-cross -j2 - uses: actions/upload-artifact@v2 @@ -178,7 +177,14 @@ jobs: - "ADM_B_NRF52840_1" - "TG-Watch" - "adafruit_feather_rp2040" + - "adafruit_itsybitsy_rp2040" + - "adafruit_neokey_trinkey_m0" + - "adafruit_proxlight_trinkey_m0" + - "adafruit_qtpy_rp2040" + - "adafruit_rotary_trinkey_m0" + - "adafruit_slide_trinkey_m0" - "aloriumtech_evo_m51" + - "aramcon2_badge" - "aramcon_badge_2019" - "arduino_mkr1300" - "arduino_mkrzero" @@ -189,6 +195,7 @@ jobs: - "bastble" - "bdmicro_vina_d21" - "bdmicro_vina_d51" + - "bdmicro_vina_d51_pcb7" - "bless_dev_board_multi_sensor" - "blm_badge" - "capablerobot_usbhub" @@ -208,6 +215,7 @@ jobs: - "datum_imu" - "datum_light" - "datum_weather" + - "dynalora_usb" - "dynossat_edu_eps" - "dynossat_edu_obc" - "electronut_labs_blip" @@ -237,6 +245,7 @@ jobs: - "hallowing_m0_express" - "hallowing_m4_express" - "hiibot_bluefi" + - "huntercat_nfc" - "ikigaisense_vita" - "imxrt1010_evk" - "imxrt1020_evk" @@ -280,6 +289,11 @@ jobs: - "pewpew10" - "pewpew_m4" - "picoplanet" + - "pimoroni_keybow2040" + - "pimoroni_picolipo_16mb" + - "pimoroni_picolipo_4mb" + - "pimoroni_picosystem" + - "pimoroni_tiny2040" - "pirkey_m0" - "pitaya_go" - "pyb_nano_v2" @@ -302,19 +316,24 @@ jobs: - "same54_xplained" - "seeeduino_wio_terminal" - "seeeduino_xiao" + - "sensebox_mcu" - "serpente" - "shirtty" - "silicognition-m4-shim" - "simmel" - "snekboard" - "sparkfun_lumidrive" + - "sparkfun_micromod_rp2040" + - "sparkfun_nrf52840_micromod" - "sparkfun_nrf52840_mini" + - "sparkfun_pro_micro_rp2040" - "sparkfun_qwiic_micro_no_flash" - "sparkfun_qwiic_micro_with_flash" - "sparkfun_redboard_turbo" - "sparkfun_samd21_dev" - "sparkfun_samd21_mini" - "sparkfun_samd51_thing_plus" + - "sparkfun_thing_plus_rp2040" - "spresense" - "stackrduino_m0_pro" - "stm32f411ce_blackpill" @@ -346,10 +365,15 @@ jobs: uses: actions/setup-python@v1 with: python-version: 3.8 + - uses: actions/checkout@v2.2.0 + with: + submodules: true + fetch-depth: 0 + - run: git fetch --recurse-submodules=no https://github.com/adafruit/circuitpython refs/tags/*:refs/tags/* - name: Install deps run: | sudo apt-get install -y gettext - pip install requests sh click setuptools awscli + pip install -r requirements-dev.txt wget --no-verbose https://adafruit-circuit-python.s3.amazonaws.com/gcc-arm-none-eabi-10-2020-q4-major-x86_64-linux.tar.bz2 sudo tar -C /usr --strip-components=1 -xaf gcc-arm-none-eabi-10-2020-q4-major-x86_64-linux.tar.bz2 - name: Versions @@ -357,13 +381,10 @@ jobs: gcc --version arm-none-eabi-gcc --version python3 --version - - uses: actions/checkout@v2.2.0 - with: - submodules: true - fetch-depth: 0 - - run: git fetch --recurse-submodules=no https://github.com/adafruit/circuitpython refs/tags/*:refs/tags/* - name: mpy-cross run: make -C mpy-cross -j2 + - name: Setup build failure matcher + run: echo "::add-matcher::$GITHUB_WORKSPACE/.github/workflows/match-build-fail.json" - name: build run: python3 -u build_release_files.py working-directory: tools @@ -395,6 +416,11 @@ jobs: uses: actions/setup-python@v1 with: python-version: 3.8 + - uses: actions/checkout@v2.2.0 + with: + submodules: true + fetch-depth: 0 + - run: git fetch --recurse-submodules=no https://github.com/adafruit/circuitpython refs/tags/*:refs/tags/* - name: Install deps run: | sudo apt-get install -y gettext @@ -406,13 +432,10 @@ jobs: gcc --version riscv64-unknown-elf-gcc --version python3 --version - - uses: actions/checkout@v2.2.0 - with: - submodules: true - fetch-depth: 0 - - run: git fetch --recurse-submodules=no https://github.com/adafruit/circuitpython refs/tags/*:refs/tags/* - name: mpy-cross run: make -C mpy-cross -j2 + - name: Setup build failure matcher + run: echo "::add-matcher::$GITHUB_WORKSPACE/.github/workflows/match-build-fail.json" - name: build run: python3 -u build_release_files.py working-directory: tools @@ -438,12 +461,17 @@ jobs: board: - "adafruit_feather_esp32s2_nopsram" - "adafruit_feather_esp32s2_tftback_nopsram" + - "adafruit_funhouse" - "adafruit_magtag_2.9_grayscale" - "adafruit_metro_esp32s2" + - "artisense_rd00" + - "atmegazero_esp32s2" - "electroniccats_bastwifi" - "espressif_kaluga_1" - "espressif_saola_1_wroom" - "espressif_saola_1_wrover" + - "franzininho_wifi_wroom" + - "franzininho_wifi_wrover" - "lilygo_ttgo_t8_s2_st7789" - "microdev_micro_s2" - "muselab_nanoesp32_s2" @@ -451,6 +479,7 @@ jobs: - "targett_module_clip_wrover" - "unexpectedmaker_feathers2" - "unexpectedmaker_feathers2_prerelease" + - "unexpectedmaker_tinys2" steps: - name: Set up Python 3.8 @@ -469,7 +498,7 @@ jobs: id: idf-cache with: path: ${{ github.workspace }}/.idf_tools - key: ${{ runner.os }}-idf-tools-${{ hashFiles('.git/modules/ports/esp32s2/esp-idf/HEAD') }}-20210128 + key: ${{ runner.os }}-idf-tools-${{ hashFiles('.git/modules/ports/esp32s2/esp-idf/HEAD') }}-20210422 - name: Clone IDF submodules run: | (cd $IDF_PATH && git submodule update --init) @@ -487,7 +516,7 @@ jobs: - name: Install CircuitPython deps run: | source $IDF_PATH/export.sh - pip install requests sh click setuptools awscli + pip install -r requirements-dev.txt sudo apt-get install -y gettext ninja-build env: IDF_PATH: ${{ github.workspace }}/ports/esp32s2/esp-idf @@ -506,6 +535,8 @@ jobs: IDF_TOOLS_PATH: ${{ github.workspace }}/.idf_tools - name: mpy-cross run: make -C mpy-cross -j2 + - name: Setup build failure matcher + run: echo "::add-matcher::$GITHUB_WORKSPACE/.github/workflows/match-build-fail.json" - name: build run: | source $IDF_PATH/export.sh diff --git a/.github/workflows/create_website_pr.yml b/.github/workflows/create_website_pr.yml index c8aca30e4a1c0..97c543da0d747 100644 --- a/.github/workflows/create_website_pr.yml +++ b/.github/workflows/create_website_pr.yml @@ -16,21 +16,21 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v2.2.0 + with: + submodules: true + fetch-depth: 0 - name: Set up Python 3.8 uses: actions/setup-python@v1 with: python-version: 3.8 - name: Install deps run: | - pip install requests sh click + pip install -r requirements-dev.txt - name: Versions run: | gcc --version python3 --version - - uses: actions/checkout@v2.2.0 - with: - submodules: true - fetch-depth: 0 - run: git fetch --recurse-submodules=no https://github.com/adafruit/circuitpython refs/tags/*:refs/tags/* - name: CircuitPython version run: git describe --dirty --tags diff --git a/.github/workflows/match-build-fail.json b/.github/workflows/match-build-fail.json new file mode 100644 index 0000000000000..938c484f26be2 --- /dev/null +++ b/.github/workflows/match-build-fail.json @@ -0,0 +1,14 @@ +{ + "problemMatcher": [ + { + "severity": "error", + "pattern": [ + { + "regexp": "^(Build .+ and \\x1b\\[31mfailed\\x1b\\[0m)$", + "message": 1 + } + ], + "owner": "build-failed" + } + ] +} diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 76bfd7786bfc6..65d5feb68ec44 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -7,7 +7,6 @@ name: pre-commit on: pull_request: push: - branches: [main] jobs: pre-commit: @@ -16,10 +15,13 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - name: Install deps - run: sudo apt-get update && sudo apt-get install -y gettext + run: | + sudo apt-add-repository -y -u ppa:pybricks/ppa + sudo apt-get install -y black gettext uncrustify + pip3 install -r requirements-dev.txt - name: Populate selected submodules run: git submodule update --init extmod/ulab - - name: set PY + - name: Set PY run: echo >>$GITHUB_ENV PY="$(python -c 'import hashlib, sys;print(hashlib.sha256(sys.version.encode()+sys.executable.encode()).hexdigest())')" - uses: actions/cache@v2 with: diff --git a/.gitignore b/.gitignore index a8814be45eb2a..54e23c379f3da 100644 --- a/.gitignore +++ b/.gitignore @@ -86,3 +86,6 @@ TAGS #################### .venv .env + +# Uncrustify formatting +*.uncrustify diff --git a/.gitmodules b/.gitmodules index 99de2c91860d1..da5b5835a6c08 100644 --- a/.gitmodules +++ b/.gitmodules @@ -171,6 +171,16 @@ [submodule "frozen/Adafruit_CircuitPython_LC709203F"] path = frozen/Adafruit_CircuitPython_LC709203F url = https://github.com/adafruit/Adafruit_CircuitPython_LC709203F +[submodule "frozen/Adafruit_CircuitPython_SimpleMath"] + path = frozen/Adafruit_CircuitPython_SimpleMath + url = https://github.com/adafruit/Adafruit_CircuitPython_SimpleMath [submodule "ports/raspberrypi/sdk"] path = ports/raspberrypi/sdk - url = https://github.com/raspberrypi/pico-sdk.git + url = https://github.com/adafruit/pico-sdk.git +[submodule "data/nvm.toml"] + path = data/nvm.toml + url = https://github.com/adafruit/nvm.toml.git + branch = main +[submodule "frozen/Adafruit_CircuitPython_MIDI"] + path = frozen/Adafruit_CircuitPython_MIDI + url = https://github.com/adafruit/Adafruit_CircuitPython_MIDI diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 322f37da46d3b..a6ad210f7aa9e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,3 +11,16 @@ repos: exclude: '^(tests/.*\.exp|tests/cmdline/.*|tests/.*/data/.*|ports/esp32s2/esp-idf-config/.*|ports/esp32s2/boards/.*/sdkconfig)' - id: trailing-whitespace exclude: '^(tests/.*\.exp|tests/cmdline/.*|tests/.*/data/.*)' +- repo: local + hooks: + - id: translations + name: Translations + entry: sh -c "if ! make check-translate; then make translate; fi" + types: [c] + pass_filenames: false + language: system + - id: formatting + name: Formatting + entry: python3 tools/codeformat.py + types_or: [c, python] + language: system diff --git a/BUILDING.md b/BUILDING.md index 10d7d8f4af7f8..256996807de49 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -85,3 +85,23 @@ Example: If your port/build includes `arm-none-eabi-gdb-py`, consider using it instead, as it can be used for better register debugging with https://github.com/bnahill/PyCortexMDebug + +# Code Quality Checks + +We apply code quality checks using pre-commit. Install pre-commit once per system with + + python3 -mpip install pre-commit + +Activate it once per git clone with + + pre-commit --install + +Pre-commit also requires some additional programs to be installed through your package manager: + + * Standard Unix tools such as make, find, etc + * The gettext package, any modern version + * uncrustify version 0.71 (0.72 is also tested) + +Each time you create a git commit, the pre-commit quality checks will be run. You can also run them e.g., with `pre-commit run foo.c` or `pre-commit run --all` to run on all files whether modified or not. + +Some pre-commit quality checks require your active attention to resolve, others (such as the formatting checks of uncrustify) are made automatically and must simply be incorporated into your code changes by committing them. diff --git a/README.rst b/README.rst index f14cf41ff3dcd..b71ad005e6a5c 100644 --- a/README.rst +++ b/README.rst @@ -51,6 +51,10 @@ Specifically useful documentation when starting out: - `CircuitPython Essentials `__ - `Example Code `__ +Code Search +------------ +GitHub doesn't currently support code search on forks. Therefore, CircuitPython doesn't have code search through GitHub because it is a fork of MicroPython. Luckily, `SourceGraph `_ has free code search for public repos like CircuitPython. So, visit `sourcegraph.com/github.com/adafruit/circuitpython `_ to search the CircuitPython codebase online. + Contributing ------------ @@ -113,10 +117,9 @@ Behavior - ``code.py`` (or ``main.py``) is run after every reload until it finishes or is interrupted. After it is done running, the vm and hardware is reinitialized. **This means you cannot read state from** - ``code.py`` **in the REPL anymore.** CircuitPython's goal for this + ``code.py`` **in the REPL anymore, as the REPL is a fresh vm.** CircuitPython's goal for this change includes reducing confusion about pins and memory being used. -- After ``code.py`` the REPL can be entered by pressing any key. It no - longer shares state with ``code.py`` so it is a fresh vm. +- After the main code is finished the REPL can be entered by pressing any key. - Autoreload state will be maintained across reload. - Adds a safe mode that does not run user code after a hard crash or brown out. The hope is that this will make it easier to fix code that @@ -126,8 +129,7 @@ Behavior - RGB status LED indicating CircuitPython state, and errors through a sequence of colored flashes. - Re-runs ``code.py`` or other main file after file system writes over USB mass storage. (Disable with ``supervisor.disable_autoreload()``) -- Entering the REPL after the main code is finished requires a key press which enters the REPL and - disables autoreload. +- Autoreload is disabled while the REPL is active. - Main is one of these: ``code.txt``, ``code.py``, ``main.py``, ``main.txt`` - Boot is one of these: ``settings.txt``, ``settings.py``, ``boot.py``, @@ -209,6 +211,7 @@ esp32s2 beta litex alpha mimxrt10xx alpha nrf stable +raspberrypi beta stm ``F4`` stable | ``others`` beta unix alpha ================ ============================================================ diff --git a/WEBUSB_README.md b/WEBUSB_README.md new file mode 100644 index 0000000000000..a257d5259cad5 --- /dev/null +++ b/WEBUSB_README.md @@ -0,0 +1,94 @@ + + +# WebUSB Serial Support + +To date, this has only been tested on one port (esp32s2), on one board (espressif_kaluga_1). + +## What it does + +If you have ever used CircuitPython on a platform with a graphical LCD display, you have probably +already seen multiple "consoles" in use (although the LCD console is "output only"). + +New compile-time option CIRCUITPY_USB_VENDOR enables an additional "console" that can be used in +parallel with the original (CDC) serial console. + +Web pages that support the WebUSB standard can connect to the "vendor" interface and activate +this WebUSB serial console at any time. + +You can type into either console, and CircuitPython output is sent to all active consoles. + +One example of a web page you can use to test drive this feature can be found at: + +https://adafruit.github.io/Adafruit_TinyUSB_Arduino/examples/webusb-serial/index.html + +## How to enable + +Update your platform's mpconfigboard.mk file to enable and disable specific types of USB interfaces. + +CIRCUITPY_USB_HID = xxx +CIRCUITPY_USB_MIDI = xxx +CIRCUITPY_USB_VENDOR = xxx + +On at least some of the hardware platforms, the maximum number of USB endpoints is fixed. +For example, on the ESP32S2, you must pick only one of the above 3 interfaces to be enabled. + +Original espressif_kaluga_1 mpconfigboard.mk settings: + +CIRCUITPY_USB_HID = 1 +CIRCUITPY_USB_MIDI = 0 +CIRCUITPY_USB_VENDOR = 0 + +Settings to enable WebUSB instead: + +CIRCUITPY_USB_HID = 0 +CIRCUITPY_USB_MIDI = 0 +CIRCUITPY_USB_VENDOR = 1 + +Notice that to enable VENDOR on ESP32-S2, we had to give up HID. There may be platforms that can have both, or even all three. + +## Implementation Notes + +CircuitPython uses the tinyusb library. + +The tinyusb library already has support for WebUSB serial. +The tinyusb examples already include a "WebUSB serial" example. + + Sidenote - The use of the term "vendor" instead of "WebUSB" was done to match tinyusb. + +Basically, this feature was ported into CircuitPython by pulling code snippets out of the +tinyusb example, and putting them where they best belonged in the CircuitPython codebase. + +There was one complication: + +tinyusb uses C preprocessor macros to define things like USB descriptors. + +CircuitPython uses a Python program (tools/gen_usb_descriptor.py) to create USB descriptors (etc.) +using "helper objects" from another repo (adafruit_usb_descriptor). This means some of the example +code had to be adapted to the new programing model, and gen_usb_descriptor gained new command-line +options to control the generated code. + +The generated files go into the "build" directory, look for autogen_usb_descriptor.c and +genhdr/autogen_usb_descriptor.h. + + +Also worth pointing out - the re-use of the CDC connect/disconnect mechanism is not actually part +of the WebUSB standard, it's more of "common idiom". We make use of it here because we need to know +when we should be paying attention to the WebUSB serial interface, and when we should ignore it.. + +## Possible future work areas + +The current code uses the existing Python infrastructure to create the Interface descriptor, but +simply outputs the code snippets from the original tinyusb demo code to create the WEBUSB_URL, +BOS, and MS_OS_20 descriptors. I suppose additional work could be done to add these to the +adafruit_usb_descriptor project, and then gen_usb_descriptor.py could be modified to make use +of them. + +Program gen_usb_descriptor.py creates objects for most interface types, regardless of whether or +not they are actually enabled. This increases the size of a generated string table. I made the +new vendor-interface-related code not do this (because some of the ARM platforms would no longer +build), but I did not go back and do this for the other interface types (CDC, MIDI, HID, etc.) +Some FLASH savings are probably possible if this is done. diff --git a/conf.py b/conf.py index 0a163e7d3c5be..2625ad63c119b 100644 --- a/conf.py +++ b/conf.py @@ -150,9 +150,11 @@ # directories to ignore when looking for source files. exclude_patterns = ["**/build*", ".git", + ".github", ".env", ".venv", ".direnv", + "data", "docs/autoapi", "docs/README.md", "drivers", @@ -178,6 +180,7 @@ "ports/cxd56/spresense-exported-sdk", "ports/esp32s2/certificates", "ports/esp32s2/esp-idf", + "ports/esp32s2/.idf_tools", "ports/esp32s2/peripherals", "ports/litex/hw", "ports/minimal", @@ -281,7 +284,7 @@ # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. -html_extra_path = ["docs/robots.txt"] +#html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. @@ -486,6 +489,8 @@ def apply(self, **kwargs): def setup(app): app.add_css_file("customstyle.css") + app.add_css_file("filter.css") + app.add_js_file("filter.js") app.add_config_value('redirects_file', 'redirects', 'env') app.connect('builder-inited', generate_redirects) app.add_transform(CoreModuleTransform) diff --git a/data/nvm.toml b/data/nvm.toml new file mode 160000 index 0000000000000..9b4a5241d8c33 --- /dev/null +++ b/data/nvm.toml @@ -0,0 +1 @@ +Subproject commit 9b4a5241d8c3310b31a7925a4f2160743890a2e4 diff --git a/devices/ble_hci/common-hal/_bleio/Adapter.c b/devices/ble_hci/common-hal/_bleio/Adapter.c index 753a886486cc2..7f0b088c4e751 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 bec1329f282ab..48d4f2e6a2e80 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 393b80459a7de..db1317f4c899a 100644 --- a/devices/ble_hci/common-hal/_bleio/Characteristic.c +++ b/devices/ble_hci/common-hal/_bleio/Characteristic.c @@ -78,16 +78,20 @@ 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_max_length(bleio_characteristic_obj_t *self) { + return self->max_length; +} + +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 +117,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 +176,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 +195,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 e8cd518808fab..8be1abef1fff0 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 ba4eb477d9106..a27c243f44834 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 0b1f26a213fba..2933bb87a5550 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 645273e2852d9..444d57fb3da8d 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 097a49f8ec32f..ffa0c172aa8dc 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 98912ba902fc7..cb14f4044b35a 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, size_t max_packet_size) { self->characteristic = characteristic; self->client = self->characteristic->service->is_remote; @@ -101,7 +101,7 @@ void common_hal_bleio_packet_buffer_construct( } if (incoming) { - if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + characteristic->max_length), false)) { + if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + max_packet_size), false)) { mp_raise_ValueError(translate("Buffer too large and unable to allocate")); } } @@ -110,12 +110,13 @@ void common_hal_bleio_packet_buffer_construct( self->packet_queued = false; self->pending_index = 0; self->pending_size = 0; - self->outgoing[0] = m_malloc(characteristic->max_length, false); - self->outgoing[1] = m_malloc(characteristic->max_length, false); + self->outgoing[0] = m_malloc(max_packet_size, false); + self->outgoing[1] = m_malloc(max_packet_size, false); } else { self->outgoing[0] = NULL; self->outgoing[1] = NULL; } + self->max_packet_size = max_packet_size; bleio_characteristic_set_observer(self->characteristic, self); } @@ -128,7 +129,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 +137,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 +148,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 +175,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 +214,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 @@ -243,7 +244,8 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { 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), + return MIN(MIN(common_hal_bleio_connection_get_max_packet_length(connection), + self->max_packet_size), self->characteristic->max_length); } } @@ -251,7 +253,7 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ // we can't tell what the largest outgoing packet length would be. return -1; } - return self->characteristic->max_length; + return MIN(self->characteristic->max_length, self->max_packet_size); } bool common_hal_bleio_packet_buffer_deinited(bleio_packet_buffer_obj_t *self) { diff --git a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h index 074c03dc690b1..34471741fe7a5 100644 --- a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h +++ b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h @@ -37,11 +37,12 @@ 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). volatile uint16_t conn_handle; + uint16_t max_packet_size; uint8_t pending_index; uint8_t write_type; bool client; diff --git a/devices/ble_hci/common-hal/_bleio/Service.c b/devices/ble_hci/common-hal/_bleio/Service.c index 5803f5309d5b9..0bf00566f2462 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 11e7d1c9605d0..dce6f13144bd2 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 a50efc3b1ec1d..f12d1e78fbdbc 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 1a0ab91c44137..59e09f7476b27 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 8d6d76415550c..5b592de83a202 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 cd9940bf06fac..18bf71834fcd9 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 4573d5e9ffe3e..5a3eb94737087 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 b34b74dc3776b..e8fdd53fd1779 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 e261a9847523c..ec1663589d9e1 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 9cdd38981ebaf..5e57142c3c0a6 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 fd74a95e8d868..44f057e43dae3 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 8117a48f45bb3..f292ceb4c3f60 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 b8efccaf46706..820246dec18b7 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 797278946a5c5..b5f9506181580 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 030fb0ca3c4f8..8fb5564eb1279 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, - - /** 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, + /** 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, }; /** @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; - - /** 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); + /** Opcode of the command */ + uint16_t op; + + /** 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); }; /** @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 660691398ebcc..02452a7886636 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 a0a2ed056c56a..b2e7fb450dfef 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/docs/design_guide.rst b/docs/design_guide.rst index 7a8c76b50775c..1bac4df61bdd0 100644 --- a/docs/design_guide.rst +++ b/docs/design_guide.rst @@ -18,7 +18,7 @@ Start libraries with the cookiecutter Cookiecutter is a tool that lets you bootstrap a new repo based on another repo. We've made one `here `_ for CircuitPython libraries that include configs for Travis CI and ReadTheDocs -along with a setup.py, license, code of conduct and readme. +along with a setup.py, license, code of conduct, readme among other files. .. code-block::sh @@ -165,6 +165,24 @@ use what. Here is more info on properties from `Python `_. +Exceptions and asserts +-------------------------------------------------------------------------------- + +Raise an appropriate `Exception `_, +along with a useful message, whenever a critical test or other condition fails. + +Example:: + + if not 0 <= pin <= 7: + raise ValueError("Pin number must be 0-7.") + +If memory is constrained and a more compact method is needed, use `assert` +instead. + +Example:: + + assert 0 <= pin <= 7, "Pin number must be 0-7." + Design for compatibility with CPython -------------------------------------------------------------------------------- @@ -234,7 +252,7 @@ At the class level document what class does and how to initialize it:: """DS3231 real-time clock. :param ~busio.I2C i2c_bus: The I2C bus the DS3231 is connected to. - :param int address: The I2C address of the device. + :param int address: The I2C address of the device. Defaults to :const:`0x40` """ def __init__(self, i2c_bus, address=0x40): @@ -249,7 +267,7 @@ Renders as: DS3231 real-time clock. :param ~busio.I2C i2c_bus: The I2C bus the DS3231 is connected to. - :param int address: The I2C address of the device. + :param int address: The I2C address of the device. Defaults to :const:`0x40` Attributes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -498,6 +516,15 @@ when using ``const()``, keep in mind these general guide lines: - If user will not need access to variable, prefix name with a leading underscore, ex: ``_SOME_CONST``. +Libraries Examples +------------------ +When adding examples, cookiecutter will add a ``_simpletest.py`` file in the examples directory for you. +Be sure to include code with the library minimal functionalities to work on a device. +You could other examples if needed featuring different +functionalities of the library. +If you add additional examples, be sure to include them in the ``examples.rst``. Naming of the examples +files should use the name of the library followed by a description, using underscore to separate them. + Sensor properties and units -------------------------------------------------------------------------------- @@ -518,7 +545,7 @@ properties. +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``gyro`` | (float, float, float) | x, y, z radians per second | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``temperature`` | float | degrees centigrade | +| ``temperature`` | float | degrees Celsius | +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``CO2`` | float | measured CO2 in ppm | +-----------------------+-----------------------+-------------------------------------------------------------------------+ @@ -526,9 +553,9 @@ properties. +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``TVOC`` | float | Total Volatile Organic Compounds in ppb | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``distance`` | float | centimeters | +| ``distance`` | float | centimeters (cm) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``proximity`` | int | non-unit-specifc proximity values (monotonic but not actual distance) | +| ``proximity`` | int | non-unit-specific proximity values (monotonic but not actual distance) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``light`` | float | non-unit-specific light levels (should be monotonic but is not lux) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ @@ -550,7 +577,7 @@ properties. +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``duty_cycle`` | int | 16-bit PWM duty cycle (regardless of output resolution) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ -| ``frequency`` | int | Hertz | +| ``frequency`` | int | Hertz (Hz) | +-----------------------+-----------------------+-------------------------------------------------------------------------+ | ``value`` | bool | Digital logic | +-----------------------+-----------------------+-------------------------------------------------------------------------+ @@ -574,9 +601,8 @@ mimic the structure in ``shared-bindings``. To test your native modules or core enhancements, follow these Adafruit Learning Guides for building local firmware to flash onto your device(s): -`SAMD21 - Build Firmware Learning Guide `_ +`Build CircuitPython `_ -`ESP8266 - Build Firmware Learning Guide `_ MicroPython compatibility -------------------------------------------------------------------------------- diff --git a/docs/index.rst b/docs/index.rst index 6dadddfc1a258..3ee76fdd8e7c9 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -46,6 +46,7 @@ Full Table of Contents ../BUILDING ../CODE_OF_CONDUCT ../license.rst + ../WEBUSB_README Indices and tables ================== diff --git a/docs/library/collections.rst b/docs/library/collections.rst index 849e8b69445fe..b7a5fb1765ea7 100644 --- a/docs/library/collections.rst +++ b/docs/library/collections.rst @@ -14,6 +14,33 @@ hold/accumulate various objects. Classes ------- +.. function:: deque(iterable, maxlen[, flags]) + + Deques (double-ended queues) are a list-like container that support O(1) + appends and pops from either side of the deque. New deques are created + using the following arguments: + + - *iterable* must be the empty tuple, and the new deque is created empty. + + - *maxlen* must be specified and the deque will be bounded to this + maximum length. Once the deque is full, any new items added will + discard items from the opposite end. + + - The optional *flags* can be 1 to check for overflow when adding items. + + As well as supporting `bool` and `len`, deque objects have the following + methods: + + .. method:: deque.append(x) + + Add *x* to the right side of the deque. + Raises IndexError if overflow checking is enabled and there is no more room left. + + .. method:: deque.popleft() + + Remove and return an item from the left side of the deque. + Raises IndexError if no items are present. + .. function:: namedtuple(name, fields) This is factory function to create a new namedtuple type with a specific diff --git a/docs/library/index.rst b/docs/library/index.rst index 181ff0109a8a4..d490ae2277416 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -39,8 +39,6 @@ with the ``u`` prefix dropped: sys.rst uctypes.rst uselect.rst - usocket.rst - ussl.rst uzlib.rst Omitted functions in the ``string`` library diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst index 31065fbe55a19..6e39a24c64611 100644 --- a/docs/library/micropython.rst +++ b/docs/library/micropython.rst @@ -81,6 +81,9 @@ Functions in a row and the lock-depth will increase, and then `heap_unlock()` must be called the same number of times to make the heap available again. + If the REPL becomes active with the heap locked then it will be forcefully + unlocked. + .. function:: kbd_intr(chr) Set the character that will raise a `KeyboardInterrupt` exception. By diff --git a/docs/library/re.rst b/docs/library/re.rst index bdcc9f52c1052..9c266a6d8fb6e 100644 --- a/docs/library/re.rst +++ b/docs/library/re.rst @@ -10,41 +10,101 @@ This module implements regular expression operations. Regular expression syntax supported is a subset of CPython ``re`` module (and actually is a subset of POSIX extended regular expressions). -Supported operators are: +Supported operators and special sequences are: -``'.'`` +``.`` Match any character. -``'[...]'`` +``[...]`` Match set of characters. Individual characters and ranges are supported, including negated sets (e.g. ``[^a-c]``). -``'^'`` +``^`` + Match the start of the string. -``'$'`` +``$`` + Match the end of the string. -``'?'`` +``?`` + Match zero or one of the previous sub-pattern. -``'*'`` +``*`` + Match zero or more of the previous sub-pattern. -``'+'`` +``+`` + Match one or more of the previous sub-pattern. -``'??'`` +``??`` + Non-greedy version of ``?``, match zero or one, with the preference + for zero. -``'*?'`` +``*?`` + Non-greedy version of ``*``, match zero or more, with the preference + for the shortest match. -``'+?'`` +``+?`` + Non-greedy version of ``+``, match one or more, with the preference + for the shortest match. -``'|'`` +``|`` + Match either the left-hand side or the right-hand side sub-patterns of + this operator. -``'(...)'`` +``(...)`` Grouping. Each group is capturing (a substring it captures can be accessed with `match.group()` method). -**NOT SUPPORTED**: Counted repetitions (``{m,n}``), more advanced assertions -(``\b``, ``\B``), named groups (``(?P...)``), non-capturing groups -(``(?:...)``), etc. +``\d`` + Matches digit. Equivalent to ``[0-9]``. +``\D`` + Matches non-digit. Equivalent to ``[^0-9]``. + +``\s`` + Matches whitespace. Equivalent to ``[ \t-\r]``. + +``\S`` + Matches non-whitespace. Equivalent to ``[^ \t-\r]``. + +``\w`` + Matches "word characters" (ASCII only). Equivalent to ``[A-Za-z0-9_]``. + +``\W`` + Matches non "word characters" (ASCII only). Equivalent to ``[^A-Za-z0-9_]``. + +``\`` + Escape character. Any other character following the backslash, except + for those listed above, is taken literally. For example, ``\*`` is + equivalent to literal ``*`` (not treated as the ``*`` operator). + Note that ``\r``, ``\n``, etc. are not handled specially, and will be + equivalent to literal letters ``r``, ``n``, etc. Due to this, it's + not recommended to use raw Python strings (``r""``) for regular + expressions. For example, ``r"\r\n"`` when used as the regular + expression is equivalent to ``"rn"``. To match CR character followed + by LF, use ``"\r\n"``. + +**NOT SUPPORTED**: + +* counted repetitions (``{m,n}``) +* named groups (``(?P...)``) +* non-capturing groups (``(?:...)``) +* more advanced assertions (``\b``, ``\B``) +* special character escapes like ``\r``, ``\n`` - use Python's own escaping + instead +* etc. + +Example:: + + import ure + + # As ure doesn't support escapes itself, use of r"" strings is not + # recommended. + regex = ure.compile("[\r\n]") + + regex.split("line1\rline2\nline3\r\n") + + # Result: + # ['line1', 'line2', 'line3', '', ''] Functions --------- @@ -64,6 +124,22 @@ Functions string for first position which matches regex (which still may be 0 if regex is anchored). +.. function:: sub(regex_str, replace, string, count=0, flags=0) + + Compile *regex_str* and search for it in *string*, replacing all matches + with *replace*, and returning the new string. + + *replace* can be a string or a function. If it is a string then escape + sequences of the form ``\`` and ``\g`` can be used to + expand to the corresponding group (or an empty string for unmatched groups). + If *replace* is a function then it must take a single argument (the match) + and should return a replacement string. + + If *count* is specified and non-zero then substitution will stop after + this many substitutions are made. The *flags* argument is ignored. + + Note: availability of this function depends on MicroPython port. + .. data:: DEBUG Flag value, display debug information about compiled expression. @@ -79,8 +155,10 @@ Compiled regular expression. Instances of this class are created using .. method:: regex.match(string) regex.search(string) + regex.sub(replace, string, count=0, flags=0) - Similar to the module-level functions :meth:`match` and :meth:`search`. + Similar to the module-level functions :meth:`match`, :meth:`search` + and :meth:`sub`. Using methods is (much) more efficient if the same regex is applied to multiple strings. @@ -93,9 +171,31 @@ Compiled regular expression. Instances of this class are created using Match objects ------------- -Match objects as returned by `match()` and `search()` methods. +Match objects as returned by `match()` and `search()` methods, and passed +to the replacement function in `sub()`. .. method:: match.group([index]) Return matching (sub)string. *index* is 0 for entire match, 1 and above for each capturing group. Only numeric groups are supported. + +.. method:: match.groups() + + Return a tuple containing all the substrings of the groups of the match. + + Note: availability of this method depends on MicroPython port. + +.. method:: match.start([index]) + match.end([index]) + + Return the index in the original string of the start or end of the + substring group that was matched. *index* defaults to the entire + group, otherwise it will select a group. + + Note: availability of these methods depends on MicroPython port. + +.. method:: match.span([index]) + + Returns the 2-tuple ``(match.start(index), match.end(index))``. + + Note: availability of this method depends on MicroPython port. diff --git a/docs/library/uctypes.rst b/docs/library/uctypes.rst index f71b00c1e46f7..fb81e3377e904 100644 --- a/docs/library/uctypes.rst +++ b/docs/library/uctypes.rst @@ -13,19 +13,91 @@ module is to define data structure layout with about the same power as the C language allows, and then access it using familiar dot-syntax to reference sub-fields. +.. warning:: + + ``uctypes`` module allows access to arbitrary memory addresses of the + machine (including I/O and control registers). Uncareful usage of it + may lead to crashes, data loss, and even hardware malfunction. + .. seealso:: Module :mod:`struct` Standard Python way to access binary data structures (doesn't scale well to large and complex structures). +Usage examples:: + + import uctypes + + # Example 1: Subset of ELF file header + # https://wikipedia.org/wiki/Executable_and_Linkable_Format#File_header + ELF_HEADER = { + "EI_MAG": (0x0 | uctypes.ARRAY, 4 | uctypes.UINT8), + "EI_DATA": 0x5 | uctypes.UINT8, + "e_machine": 0x12 | uctypes.UINT16, + } + + # "f" is an ELF file opened in binary mode + buf = f.read(uctypes.sizeof(ELF_HEADER, uctypes.LITTLE_ENDIAN)) + header = uctypes.struct(uctypes.addressof(buf), ELF_HEADER, uctypes.LITTLE_ENDIAN) + assert header.EI_MAG == b"\x7fELF" + assert header.EI_DATA == 1, "Oops, wrong endianness. Could retry with uctypes.BIG_ENDIAN." + print("machine:", hex(header.e_machine)) + + + # Example 2: In-memory data structure, with pointers + COORD = { + "x": 0 | uctypes.FLOAT32, + "y": 4 | uctypes.FLOAT32, + } + + STRUCT1 = { + "data1": 0 | uctypes.UINT8, + "data2": 4 | uctypes.UINT32, + "ptr": (8 | uctypes.PTR, COORD), + } + + # Suppose you have address of a structure of type STRUCT1 in "addr" + # uctypes.NATIVE is optional (used by default) + struct1 = uctypes.struct(addr, STRUCT1, uctypes.NATIVE) + print("x:", struct1.ptr[0].x) + + + # Example 3: Access to CPU registers. Subset of STM32F4xx WWDG block + WWDG_LAYOUT = { + "WWDG_CR": (0, { + # BFUINT32 here means size of the WWDG_CR register + "WDGA": 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32, + "T": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32, + }), + "WWDG_CFR": (4, { + "EWI": 9 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32, + "WDGTB": 7 << uctypes.BF_POS | 2 << uctypes.BF_LEN | uctypes.BFUINT32, + "W": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32, + }), + } + + WWDG = uctypes.struct(0x40002c00, WWDG_LAYOUT) + + WWDG.WWDG_CFR.WDGTB = 0b10 + WWDG.WWDG_CR.WDGA = 1 + print("Current counter:", WWDG.WWDG_CR.T) + Defining structure layout ------------------------- Structure layout is defined by a "descriptor" - a Python dictionary which encodes field names as keys and other properties required to access them as -associated values. Currently, uctypes requires explicit specification of -offsets for each field. Offset are given in bytes from a structure start. +associated values:: + + { + "field1": , + "field2": , + ... + } + +Currently, ``uctypes`` requires explicit specification of offsets for each +field. Offset are given in bytes from the structure start. Following are encoding examples for various field types: @@ -33,7 +105,7 @@ Following are encoding examples for various field types: "field_name": offset | uctypes.UINT32 - in other words, value is scalar type identifier ORed with field offset + in other words, the value is a scalar type identifier ORed with a field offset (in bytes) from the start of the structure. * Recursive structures:: @@ -43,9 +115,11 @@ Following are encoding examples for various field types: "b1": 1 | uctypes.UINT8, }) - i.e. value is a 2-tuple, first element of which is offset, and second is + i.e. value is a 2-tuple, first element of which is an offset, and second is a structure descriptor dictionary (note: offsets in recursive descriptors - are relative to the structure it defines). + are relative to the structure it defines). Of course, recursive structures + can be specified not just by a literal dictionary, but by referring to a + structure descriptor dictionary (defined earlier) by name. * Arrays of primitive types:: @@ -53,42 +127,42 @@ Following are encoding examples for various field types: i.e. value is a 2-tuple, first element of which is ARRAY flag ORed with offset, and second is scalar element type ORed number of elements - in array. + in the array. * Arrays of aggregate types:: "arr2": (offset | uctypes.ARRAY, size, {"b": 0 | uctypes.UINT8}), i.e. value is a 3-tuple, first element of which is ARRAY flag ORed - with offset, second is a number of elements in array, and third is - descriptor of element type. + with offset, second is a number of elements in the array, and third is + a descriptor of element type. * Pointer to a primitive type:: "ptr": (offset | uctypes.PTR, uctypes.UINT8), i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, and second is scalar element type. + with offset, and second is a scalar element type. * Pointer to an aggregate type:: "ptr2": (offset | uctypes.PTR, {"b": 0 | uctypes.UINT8}), i.e. value is a 2-tuple, first element of which is PTR flag ORed - with offset, second is descriptor of type pointed to. + with offset, second is a descriptor of type pointed to. * Bitfields:: "bitf0": offset | uctypes.BFUINT16 | lsbit << uctypes.BF_POS | bitsize << uctypes.BF_LEN, - i.e. value is type of scalar value containing given bitfield (typenames are - similar to scalar types, but prefixes with "BF"), ORed with offset for + i.e. value is a type of scalar value containing given bitfield (typenames are + similar to scalar types, but prefixes with ``BF``), ORed with offset for scalar value containing the bitfield, and further ORed with values for - bit offset and bit length of the bitfield within scalar value, shifted by - BF_POS and BF_LEN positions, respectively. Bitfield position is counted - from the least significant bit, and is the number of right-most bit of a - field (in other words, it's a number of bits a scalar needs to be shifted - right to extract the bitfield). + bit position and bit length of the bitfield within the scalar value, shifted by + BF_POS and BF_LEN bits, respectively. A bitfield position is counted + from the least significant bit of the scalar (having position of 0), and + is the number of right-most bit of a field (in other words, it's a number + of bits a scalar needs to be shifted right to extract the bitfield). In the example above, first a UINT16 value will be extracted at offset 0 (this detail may be important when accessing hardware registers, where @@ -128,10 +202,11 @@ Module contents Layout type for a native structure - with data endianness and alignment conforming to the ABI of the system on which MicroPython runs. -.. function:: sizeof(struct) +.. function:: sizeof(struct, layout_type=NATIVE) - Return size of data structure in bytes. Argument can be either structure - class or specific instantiated structure object (or its aggregate field). + Return size of data structure in bytes. The *struct* argument can be + either a structure class or a specific instantiated structure object + (or its aggregate field). .. function:: addressof(obj) @@ -153,6 +228,35 @@ Module contents so it can be both written too, and you will access current value at the given memory address. +.. data:: UINT8 + INT8 + UINT16 + INT16 + UINT32 + INT32 + UINT64 + INT64 + + Integer types for structure descriptors. Constants for 8, 16, 32, + and 64 bit types are provided, both signed and unsigned. + +.. data:: FLOAT32 + FLOAT64 + + Floating-point types for structure descriptors. + +.. data:: VOID + + ``VOID`` is an alias for ``UINT8``, and is provided to conviniently define + C's void pointers: ``(uctypes.PTR, uctypes.VOID)``. + +.. data:: PTR + ARRAY + + Type constants for pointers and arrays. Note that there is no explicit + constant for structures, it's implicit: an aggregate type without ``PTR`` + or ``ARRAY`` flags is a structure. + Structure descriptors and instantiating structure objects --------------------------------------------------------- @@ -165,7 +269,7 @@ following sources: system. Lookup these addresses in datasheet for a particular MCU/SoC. * As a return value from a call to some FFI (Foreign Function Interface) function. -* From uctypes.addressof(), when you want to pass arguments to an FFI +* From `uctypes.addressof()`, when you want to pass arguments to an FFI function, or alternatively, to access some data for I/O (for example, data read from a file or network socket). @@ -183,30 +287,41 @@ the standard subscript operator ``[]`` - both read and assigned to. If a field is a pointer, it can be dereferenced using ``[0]`` syntax (corresponding to C ``*`` operator, though ``[0]`` works in C too). -Subscripting a pointer with other integer values but 0 are supported too, +Subscripting a pointer with other integer values but 0 are also supported, with the same semantics as in C. -Summing up, accessing structure fields generally follows C syntax, +Summing up, accessing structure fields generally follows the C syntax, except for pointer dereference, when you need to use ``[0]`` operator instead of ``*``. Limitations ----------- -Accessing non-scalar fields leads to allocation of intermediate objects +1. Accessing non-scalar fields leads to allocation of intermediate objects to represent them. This means that special care should be taken to layout a structure which needs to be accessed when memory allocation is disabled (e.g. from an interrupt). The recommendations are: -* Avoid nested structures. For example, instead of +* Avoid accessing nested structures. For example, instead of ``mcu_registers.peripheral_a.register1``, define separate layout descriptors for each peripheral, to be accessed as - ``peripheral_a.register1``. -* Avoid other non-scalar data, like array. For example, instead of - ``peripheral_a.register[0]`` use ``peripheral_a.register0``. - -Note that these recommendations will lead to decreased readability -and conciseness of layouts, so they should be used only if the need -to access structure fields without allocation is anticipated (it's -even possible to define 2 parallel layouts - one for normal usage, -and a restricted one to use when memory allocation is prohibited). + ``peripheral_a.register1``. Or just cache a particular peripheral: + ``peripheral_a = mcu_registers.peripheral_a``. If a register + consists of multiple bitfields, you would need to cache references + to a particular register: ``reg_a = mcu_registers.peripheral_a.reg_a``. +* Avoid other non-scalar data, like arrays. For example, instead of + ``peripheral_a.register[0]`` use ``peripheral_a.register0``. Again, + an alternative is to cache intermediate values, e.g. + ``register0 = peripheral_a.register[0]``. + +2. Range of offsets supported by the ``uctypes`` module is limited. +The exact range supported is considered an implementation detail, +and the general suggestion is to split structure definitions to +cover from a few kilobytes to a few dozen of kilobytes maximum. +In most cases, this is a natural situation anyway, e.g. it doesn't make +sense to define all registers of an MCU (spread over 32-bit address +space) in one structure, but rather a peripheral block by peripheral +block. In some extreme cases, you may need to split a structure in +several parts artificially (e.g. if accessing native data structure +with multi-megabyte array in the middle, though that would be a very +synthetic case). diff --git a/docs/library/uselect.rst b/docs/library/uselect.rst index a2b408b2060ed..cdf12fac26b96 100644 --- a/docs/library/uselect.rst +++ b/docs/library/uselect.rst @@ -47,13 +47,18 @@ Methods *eventmask* defaults to ``uselect.POLLIN | uselect.POLLOUT``. + It is OK to call this function multiple times for the same *obj*. + Successive calls will update *obj*'s eventmask to the value of + *eventmask* (i.e. will behave as `modify()`). + .. method:: poll.unregister(obj) Unregister *obj* from polling. .. method:: poll.modify(obj, eventmask) - Modify the *eventmask* for *obj*. + Modify the *eventmask* for *obj*. If *obj* is not registered, `OSError` + is raised with error of ENOENT. .. method:: poll.poll(timeout=-1) diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst deleted file mode 100644 index 2115085a311d5..0000000000000 --- a/docs/library/usocket.rst +++ /dev/null @@ -1,336 +0,0 @@ -******************************* -:mod:`usocket` -- socket module -******************************* - -.. include:: ../templates/unsupported_in_circuitpython.inc - -.. module:: usocket - :synopsis: socket module - -|see_cpython_module| :mod:`cpython:socket`. - -This module provides access to the BSD socket interface. - -.. admonition:: Difference to CPython - :class: attention - - For efficiency and consistency, socket objects in MicroPython implement a ``stream`` - (file-like) interface directly. In CPython, you need to convert a socket to - a file-like object using `makefile()` method. This method is still supported - by MicroPython (but is a no-op), so where compatibility with CPython matters, - be sure to use it. - -Socket address format(s) ------------------------- - -The native socket address format of the ``usocket`` module is an opaque data type -returned by `getaddrinfo` function, which must be used to resolve textual address -(including numeric addresses):: - - sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1] - # You must use getaddrinfo() even for numeric addresses - sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1] - # Now you can use that address - sock.connect(addr) - -Using `getaddrinfo` is the most efficient (both in terms of memory and processing -power) and portable way to work with addresses. - -However, ``socket`` module (note the difference with native MicroPython -``usocket`` module described here) provides CPython-compatible way to specify -addresses using tuples, as described below. - -Summing up: - -* Always use `getaddrinfo` when writing portable applications. -* Tuple addresses described below can be used as a shortcut for - quick hacks and interactive use, if your port supports them. - -Tuple address format for ``socket`` module: - -* IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with - dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and - integer port number in the range 1-65535. Note the domain names are not - accepted as *ipv4_address*, they should be resolved first using - `usocket.getaddrinfo()`. -* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address* - is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``, - and *port* is an integer port number in the range 1-65535. *flowinfo* - must be 0. *scopeid* is the interface scope identifier for link-local - addresses. Note the domain names are not accepted as *ipv6_address*, - they should be resolved first using `usocket.getaddrinfo()`. - -Functions ---------- - -.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP) - - Create a new socket using the given address family, socket type and - protocol number. Note that specifying *proto* in most cases is not - required (and not recommended, as some MicroPython ports may omit - ``IPPROTO_*`` constants). Instead, *type* argument will select needed - protocol automatically:: - - # Create STREAM TCP socket - socket(AF_INET, SOCK_STREAM) - # Create DGRAM UDP socket - socket(AF_INET, SOCK_DGRAM) - -.. function:: getaddrinfo(host, port) - - Translate the host/port argument into a sequence of 5-tuples that contain all the - necessary arguments for creating a socket connected to that service. The list of - 5-tuples has following structure:: - - (family, type, proto, canonname, sockaddr) - - The following example shows how to connect to a given url:: - - s = usocket.socket() - s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1]) - - .. admonition:: Difference to CPython - :class: attention - - CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case - of error in this function. MicroPython doesn't have ``socket.gaierror`` - and raises OSError directly. Note that error numbers of `getaddrinfo()` - form a separate namespace and may not match error numbers from - :py:mod:`uerrno` module. To distinguish `getaddrinfo()` errors, they are - represented by negative numbers, whereas standard system errors are - positive numbers (error numbers are accessible using ``e.args[0]`` property - from an exception object). The use of negative values is a provisional - detail which may change in the future. - -.. function:: inet_ntop(af, bin_addr) - - Convert a binary network address *bin_addr* of the given address family *af* - to a textual representation:: - - >>> usocket.inet_ntop(usocket.AF_INET, b"\x7f\0\0\1") - '127.0.0.1' - -.. function:: inet_pton(af, txt_addr) - - Convert a textual network address *txt_addr* of the given address family *af* - to a binary representation:: - - >>> usocket.inet_pton(usocket.AF_INET, "1.2.3.4") - b'\x01\x02\x03\x04' - -Constants ---------- - -.. data:: AF_INET - AF_INET6 - - Address family types. Availability depends on a particular ``MicroPython port``. - -.. data:: SOCK_STREAM - SOCK_DGRAM - - Socket types. - -.. data:: IPPROTO_UDP - IPPROTO_TCP - - IP protocol numbers. Availability depends on a particular ``MicroPython port``. - Note that you don't need to specify these in a call to `usocket.socket()`, - because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and - `SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants - is as an argument to `usocket.socket.setsockopt()`. - -.. data:: usocket.SOL_* - - Socket option levels (an argument to `usocket.socket.setsockopt()`). The exact - inventory depends on a ``MicroPython port``. - -.. data:: usocket.SO_* - - Socket options (an argument to `usocket.socket.setsockopt()`). The exact - inventory depends on a ``MicroPython port``. - -Constants specific to WiPy: - -.. data:: IPPROTO_SEC - - Special protocol value to create SSL-compatible socket. - -class socket -============ - -Methods -------- - -.. method:: socket.close() - - Mark the socket closed and release all resources. Once that happens, all future operations - on the socket object will fail. The remote end will receive EOF indication if - supported by protocol. - - Sockets are automatically closed when they are garbage-collected, but it is recommended - to `close()` them explicitly as soon you finished working with them. - -.. method:: socket.bind(address) - - Bind the socket to *address*. The socket must not already be bound. - -.. method:: socket.listen([backlog]) - - Enable a server to accept connections. If *backlog* is specified, it must be at least 0 - (if it's lower, it will be set to 0); and specifies the number of unaccepted connections - that the system will allow before refusing new connections. If not specified, a default - reasonable value is chosen. - -.. method:: socket.accept() - - Accept a connection. The socket must be bound to an address and listening for connections. - The return value is a pair (conn, address) where conn is a new socket object usable to send - and receive data on the connection, and address is the address bound to the socket on the - other end of the connection. - -.. method:: socket.connect(address) - - Connect to a remote socket at *address*. - -.. method:: socket.send(bytes) - - Send data to the socket. The socket must be connected to a remote socket. - Returns number of bytes sent, which may be smaller than the length of data - ("short write"). - -.. method:: socket.sendall(bytes) - - Send all data to the socket. The socket must be connected to a remote socket. - Unlike `send()`, this method will try to send all of data, by sending data - chunk by chunk consecutively. - - The behavior of this method on non-blocking sockets is undefined. Due to this, - on MicroPython, it's recommended to use `write()` method instead, which - has the same "no short writes" policy for blocking sockets, and will return - number of bytes sent on non-blocking sockets. - -.. method:: socket.recv(bufsize) - - Receive data from the socket. The return value is a bytes object representing the data - received. The maximum amount of data to be received at once is specified by bufsize. - -.. method:: socket.sendto(bytes, address) - - Send data to the socket. The socket should not be connected to a remote socket, since the - destination socket is specified by *address*. - -.. method:: socket.recvfrom(bufsize) - - Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a - bytes object representing the data received and *address* is the address of the socket sending - the data. - -.. method:: socket.setsockopt(level, optname, value) - - Set the value of the given socket option. The needed symbolic constants are defined in the - socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing - a buffer. - -.. method:: socket.settimeout(value) - - **Note**: Not every port supports this method, see below. - - Set a timeout on blocking socket operations. The value argument can be a nonnegative floating - point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations - will raise an `OSError` exception if the timeout period value has elapsed before the operation has - completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket - is put in blocking mode. - - Not every ``MicroPython port`` supports this method. A more portable and - generic solution is to use `uselect.poll` object. This allows to wait on - multiple objects at the same time (and not just on sockets, but on generic - ``stream`` objects which support polling). Example:: - - # Instead of: - s.settimeout(1.0) # time in seconds - s.read(10) # may timeout - - # Use: - poller = uselect.poll() - poller.register(s, uselect.POLLIN) - res = poller.poll(1000) # time in milliseconds - if not res: - # s is still not ready for input, i.e. operation timed out - - .. admonition:: Difference to CPython - :class: attention - - CPython raises a ``socket.timeout`` exception in case of timeout, - which is an `OSError` subclass. MicroPython raises an OSError directly - instead. If you use ``except OSError:`` to catch the exception, - your code will work both in MicroPython and CPython. - -.. method:: socket.setblocking(flag) - - Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, - else to blocking mode. - - This method is a shorthand for certain `settimeout()` calls: - - * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` - * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)`` - -.. method:: socket.makefile(mode='rb', buffering=0) - - Return a file object associated with the socket. The exact returned type depends on the arguments - given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb'). - CPython's arguments: *encoding*, *errors* and *newline* are not supported. - - .. admonition:: Difference to CPython - :class: attention - - As MicroPython doesn't support buffered streams, values of *buffering* - parameter is ignored and treated as if it was 0 (unbuffered). - - .. admonition:: Difference to CPython - :class: attention - - Closing the file object returned by makefile() WILL close the - original socket as well. - -.. method:: socket.read([size]) - - Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it - reads all data available from the socket until EOF; as such the method will not return until - the socket is closed. This function tries to read as much data as - requested (no "short reads"). This may be not possible with - non-blocking socket though, and then less data will be returned. - -.. method:: socket.readinto(buf[, nbytes]) - - Read bytes into the *buf*. If *nbytes* is specified then read at most - that many bytes. Otherwise, read at most *len(buf)* bytes. Just as - `read()`, this method follows "no short reads" policy. - - Return value: number of bytes read and stored into *buf*. - -.. method:: socket.readline() - - Read a line, ending in a newline character. - - Return value: the line read. - -.. method:: socket.write(buf) - - Write the buffer of bytes to the socket. This function will try to - write all data to a socket (no "short writes"). This may be not possible - with a non-blocking socket though, and returned value will be less than - the length of *buf*. - - Return value: number of bytes written. - -.. exception:: usocket.error - - MicroPython does NOT have this exception. - - .. admonition:: Difference to CPython - :class: attention - - CPython used to have a ``socket.error`` exception which is now deprecated, - and is an alias of `OSError`. In MicroPython, use `OSError` directly. diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst deleted file mode 100644 index 91a64b025fca7..0000000000000 --- a/docs/library/ussl.rst +++ /dev/null @@ -1,50 +0,0 @@ -:mod:`ussl` -- SSL/TLS module -============================= - -.. include:: ../templates/unsupported_in_circuitpython.inc - -.. module:: ussl - :synopsis: TLS/SSL wrapper for socket objects - -|see_cpython_module| :mod:`cpython:ssl`. - -This module provides access to Transport Layer Security (previously and -widely known as “Secure Sockets Layer”) encryption and peer authentication -facilities for network sockets, both client-side and server-side. - -Functions ---------- - -.. function:: ussl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None) - - Takes a ``stream`` *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type), - and returns an instance of ssl.SSLSocket, which wraps the underlying stream in - an SSL context. Returned object has the usual ``stream`` interface methods like - ``read()``, ``write()``, etc. In MicroPython, the returned object does not expose - socket interface and methods like ``recv()``, ``send()``. In particular, a - server-side SSL socket should be created from a normal socket returned from - :meth:`~usocket.socket.accept()` on a non-SSL listening server socket. - - Depending on the underlying module implementation in a particular - ``MicroPython port``, some or all keyword arguments above may be not supported. - -.. warning:: - - Some implementations of ``ussl`` module do NOT validate server certificates, - which makes an SSL connection established prone to man-in-the-middle attacks. - -Exceptions ----------- - -.. data:: ssl.SSLError - - This exception does NOT exist. Instead its base class, OSError, is used. - -Constants ---------- - -.. data:: ussl.CERT_NONE - ussl.CERT_OPTIONAL - ussl.CERT_REQUIRED - - Supported values for *cert_reqs* parameter. diff --git a/docs/robots.txt b/docs/robots.txt deleted file mode 100644 index ad3189d42c3da..0000000000000 --- a/docs/robots.txt +++ /dev/null @@ -1,6 +0,0 @@ -User-agent: * -Allow: /*/latest/ -Allow: /en/latest/ # Fallback for bots that don't understand wildcards -Allow: /*/6.0.x/ -Allow: /en/6.0.x/ # Fallback for bots that don't understand wildcards -Disallow: / diff --git a/docs/shared_bindings_matrix.py b/docs/shared_bindings_matrix.py index e62b1d2186ae6..e87769f06c850 100644 --- a/docs/shared_bindings_matrix.py +++ b/docs/shared_bindings_matrix.py @@ -32,6 +32,39 @@ SUPPORTED_PORTS = ['atmel-samd', 'cxd56', 'esp32s2', 'litex', 'mimxrt10xx', 'nrf', 'raspberrypi', 'stm'] +aliases_by_board = { + "circuitplayground_express": [ + "circuitplayground_express_4h", + "circuitplayground_express_digikey_pycon2019", + ], + "pybadge": ["edgebadge"], + "pyportal": ["pyportal_pynt"], + "gemma_m0": ["gemma_m0_pycon2018"], + "pewpew10": ["pewpew13"], +} + +aliases_brand_names = { + "circuitplayground_express_4h": + "Adafruit Circuit Playground Express 4-H", + "circuitplayground_express_digikey_pycon2019": + "Circuit Playground Express Digi-Key PyCon 2019", + "edgebadge": + "Adafruit EdgeBadge", + "pyportal_pynt": + "Adafruit PyPortal Pynt", + "gemma_m0_pycon2018": + "Adafruit Gemma M0 PyCon 2018", + "pewpew13": + "PewPew 13", +} + +additional_modules = { + "fontio": "CIRCUITPY_DISPLAYIO", + "terminalio": "CIRCUITPY_DISPLAYIO", + # "socket": "CIRCUITPY_NETWORK", + "adafruit_bus_device": "CIRCUITPY_BUSDEVICE", +} + def get_circuitpython_root_dir(): """ The path to the root './circuitpython' directory """ @@ -71,8 +104,11 @@ def build_module_map(): full_build = False for module in modules: full_name = module - search_name = module.lstrip("_") - re_pattern = "CIRCUITPY_{}\s*\??=\s*(.+)".format(search_name.upper()) + if module in additional_modules: + search_identifier = additional_modules[module] + else: + search_identifier = 'CIRCUITPY_'+module.lstrip("_").upper() + re_pattern = f"{re.escape(search_identifier)}\s*\??=\s*(.+)" find_config = re.findall(re_pattern, configs) if not find_config: continue @@ -84,11 +120,12 @@ def build_module_map(): else: default_val = "None" - base[search_name] = { + base[module] = { "name": full_name, "full_build": str(full_build), "default_value": default_val, - "excluded": {} + "excluded": {}, + "key": search_identifier, } return base @@ -164,14 +201,28 @@ def support_matrix(arg): board_modules = [] for module in base: - key = f'CIRCUITPY_{module.upper()}' + key = base[module]['key'] if int(lookup_setting(settings, key, '0')): board_modules.append(base[module]['name']) + board_modules.sort() + + # generate alias boards too + board_matrix = [(board_name, board_modules)] + if entry.name in aliases_by_board: + for alias in aliases_by_board[entry.name]: + if use_branded_name: + if alias in aliases_brand_names: + alias = aliases_brand_names[alias] + else: + alias = alias.replace("_"," ").title() + board_matrix.append( (alias, board_modules) ) - return (board_name, sorted(board_modules)) + return board_matrix # this is now a list of (board,modules) executor = ThreadPoolExecutor(max_workers=os.cpu_count()) - boards = dict(sorted(executor.map(support_matrix, all_ports_all_boards()))) + mapped_exec = executor.map(support_matrix, all_ports_all_boards()) + # flatmap with comprehensions + boards = dict(sorted([board for matrix in mapped_exec for board in matrix])) #print(json.dumps(boards, indent=2)) return boards diff --git a/docs/static/filter.css b/docs/static/filter.css new file mode 100644 index 0000000000000..12efe14a40666 --- /dev/null +++ b/docs/static/filter.css @@ -0,0 +1,17 @@ +#support-matrix-filter-block { position: relative; } +#support-matrix-filter { + width: 100%; +} +#support-matrix-filter-num { + position: absolute; + right: 10px; + top: 4px; +} +.support-matrix-table .this_module code, +.support-matrix-table .this_module span { + background: black; + color: white; +} +.support-matrix-table .board_hidden { + display: none; +} diff --git a/docs/static/filter.js b/docs/static/filter.js new file mode 100644 index 0000000000000..9dc46a9eed85e --- /dev/null +++ b/docs/static/filter.js @@ -0,0 +1,86 @@ +$(() => { + var urlTimeout = null; + function setURL(query, value) { + clearTimeout(urlTimeout); + + urlTimeout = setTimeout(function() { + var url = new URL(window.location.href); + console.log(query,value,value.length,!value.length); + if (!value.length) { + console.log + url.searchParams.delete(query); + } else if (Array.isArray(value)) { + url.searchParams.delete(query); + value.forEach(function(v) { + url.searchParams.append(query, v); + }) + } else { + url.searchParams.set(query, value); + } + + window.history.pushState(null, document.title, url.href); + }, 1000); + } + + function handlePageLoad() { + var url = new URL(window.location.href); + //get values from URL + var filters = url.searchParams.getAll('filter'); + search_terms = filters.join(" "); + $("#support-matrix-filter").val(search_terms); + run_filter(); + } + + function filter_boards(search_string) { + $(".board_hidden").removeClass("board_hidden"); + $(".this_module").removeClass("this_module"); + var nboards = $(".support-matrix-table tbody tr").length; + if(search_string.trim() == "") { + $("#support-matrix-filter-num").html("(all)"); + setURL("filter",[]); + return; + } + var list_search = search_string.split(" ").filter(i => i); + var nvisible = 0; + $(".support-matrix-table tbody tr").each( (index,item) => { + var name = $(item).find("td:first-child p").html(); + var modules = $(item).find("a.reference.internal"); + var matching_all = true; + // + list_search.forEach((sstring) => { + var matching = (sstring[0] == "-"); + for(var modi = 0; modi < modules.length; ++modi) { + module = modules[modi]; + var mod_name = module.firstChild.firstChild.textContent; + if(sstring[0] == "-") { + if(mod_name.match(sstring.substr(1))) { + matching = false; + break; + } + } else { + if(mod_name.match(sstring)) { + $(module).addClass("this_module"); + matching = true; + } + } + } + matching_all = matching_all && matching; + }); + if(!matching_all) { + $(item).addClass("board_hidden"); + } else { + nvisible += 1; + } + }); + $("#support-matrix-filter-num").html(`(${nvisible}/${nboards})`); + setURL("filter",list_search); + } + + function run_filter() { + var search_string = $("#support-matrix-filter").val(); + filter_boards(search_string); + } + $("#support-matrix-filter").on("keyup", run_filter); + // $(document).on("keyup", "#support-matrix-filter", run_filter); + handlePageLoad(); +}); diff --git a/drivers/bus/softqspi.c b/drivers/bus/softqspi.c deleted file mode 100644 index 87f7c8ae8c17b..0000000000000 --- a/drivers/bus/softqspi.c +++ /dev/null @@ -1,203 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * SPDX-FileCopyrightText: Copyright (c) 2017-2018 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "drivers/bus/qspi.h" - -#define CS_LOW(self) mp_hal_pin_write(self->cs, 0) -#define CS_HIGH(self) mp_hal_pin_write(self->cs, 1) - -#ifdef MICROPY_HW_SOFTQSPI_SCK_LOW - -// Use externally provided functions for SCK control and IO reading -#define SCK_LOW(self) MICROPY_HW_SOFTQSPI_SCK_LOW(self) -#define SCK_HIGH(self) MICROPY_HW_SOFTQSPI_SCK_HIGH(self) -#define NIBBLE_READ(self) MICROPY_HW_SOFTQSPI_NIBBLE_READ(self) - -#else - -// Use generic pin functions for SCK control and IO reading -#define SCK_LOW(self) mp_hal_pin_write(self->clk, 0) -#define SCK_HIGH(self) mp_hal_pin_write(self->clk, 1) -#define NIBBLE_READ(self) ( \ - mp_hal_pin_read(self->io0) \ - | (mp_hal_pin_read(self->io1) << 1) \ - | (mp_hal_pin_read(self->io2) << 2) \ - | (mp_hal_pin_read(self->io3) << 3)) - -#endif - -STATIC void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) { - mp_hal_pin_write(self->io0, v & 1); - mp_hal_pin_write(self->io1, (v >> 1) & 1); - mp_hal_pin_write(self->io2, (v >> 2) & 1); - mp_hal_pin_write(self->io3, (v >> 3) & 1); -} - -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; - - switch (cmd) { - case MP_QSPI_IOCTL_INIT: - mp_hal_pin_high(self->cs); - mp_hal_pin_output(self->cs); - - // 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_output(self->io0); - mp_hal_pin_input(self->io1); - mp_hal_pin_write(self->io2, 1); - mp_hal_pin_output(self->io2); - mp_hal_pin_write(self->io3, 1); - mp_hal_pin_output(self->io3); - break; - } - - return 0; // success -} - -STATIC void mp_soft_qspi_transfer(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *src, uint8_t *dest) { - // Will run as fast as possible, limited only by CPU speed and GPIO time - mp_hal_pin_input(self->io1); - mp_hal_pin_output(self->io0); - if (self->io3) { - mp_hal_pin_write(self->io2, 1); - mp_hal_pin_output(self->io2); - mp_hal_pin_write(self->io3, 1); - mp_hal_pin_output(self->io3); - } - if (src) { - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->io0, (data_out >> 7) & 1); - mp_hal_pin_write(self->clk, 1); - data_in = (data_in << 1) | mp_hal_pin_read(self->io1); - mp_hal_pin_write(self->clk, 0); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - } else { - for (size_t i = 0; i < len; ++i) { - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j) { - mp_hal_pin_write(self->clk, 1); - data_in = (data_in << 1) | mp_hal_pin_read(self->io1); - mp_hal_pin_write(self->clk, 0); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - } -} - -STATIC void mp_soft_qspi_qread(mp_soft_qspi_obj_t *self, size_t len, uint8_t *buf) { - // Make all IO lines input - mp_hal_pin_input(self->io2); - mp_hal_pin_input(self->io3); - mp_hal_pin_input(self->io0); - mp_hal_pin_input(self->io1); - - // Will run as fast as possible, limited only by CPU speed and GPIO time - while (len--) { - SCK_HIGH(self); - uint8_t data_in = NIBBLE_READ(self); - SCK_LOW(self); - SCK_HIGH(self); - *buf++ = (data_in << 4) | NIBBLE_READ(self); - SCK_LOW(self); - } -} - -STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *buf) { - // Make all IO lines output - mp_hal_pin_output(self->io2); - mp_hal_pin_output(self->io3); - mp_hal_pin_output(self->io0); - mp_hal_pin_output(self->io1); - - // Will run as fast as possible, limited only by CPU speed and GPIO time - for (size_t i = 0; i < len; ++i) { - nibble_write(self, buf[i] >> 4); - SCK_HIGH(self); - SCK_LOW(self); - - nibble_write(self, buf[i]); - SCK_HIGH(self); - SCK_LOW(self); - } - - //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; - uint32_t cmd_buf = cmd | data << 8; - CS_LOW(self); - 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; - uint8_t cmd_buf[4] = {cmd, addr >> 16, addr >> 8, addr}; - CS_LOW(self); - mp_soft_qspi_transfer(self, 4, cmd_buf, NULL); - mp_soft_qspi_transfer(self, len, src, NULL); - CS_HIGH(self); -} - -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; - uint32_t cmd_buf = cmd; - CS_LOW(self); - 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; - uint8_t cmd_buf[7] = {cmd, addr >> 16, addr >> 8, addr}; - CS_LOW(self); - mp_soft_qspi_transfer(self, 1, cmd_buf, NULL); - mp_soft_qspi_qwrite(self, 6, &cmd_buf[1]); // 3 addr bytes, 1 extra byte (0), 2 dummy bytes (4 dummy cycles) - mp_soft_qspi_qread(self, len, dest); - CS_HIGH(self); -} - -const mp_qspi_proto_t mp_soft_qspi_proto = { - .ioctl = mp_soft_qspi_ioctl, - .write_cmd_data = mp_soft_qspi_write_cmd_data, - .write_cmd_addr_data = mp_soft_qspi_write_cmd_addr_data, - .read_cmd = mp_soft_qspi_read_cmd, - .read_cmd_qaddr_qdata = mp_soft_qspi_read_cmd_qaddr_qdata, -}; diff --git a/drivers/bus/softspi.c b/drivers/bus/softspi.c deleted file mode 100644 index feb8e00d38b61..0000000000000 --- a/drivers/bus/softspi.c +++ /dev/null @@ -1,105 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * SPDX-FileCopyrightText: Copyright (c) 2016-2018 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#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; - - switch (cmd) { - case MP_SPI_IOCTL_INIT: - mp_hal_pin_write(self->sck, self->polarity); - mp_hal_pin_output(self->sck); - mp_hal_pin_output(self->mosi); - mp_hal_pin_input(self->miso); - break; - - case MP_SPI_IOCTL_DEINIT: - break; - } - - return 0; -} - -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; - uint32_t delay_half = self->delay_half; - - // only MSB transfer is implemented - - // If a port defines MICROPY_HW_SOFTSPI_MIN_DELAY, and the configured - // delay_half is equal to this value, then the software SPI implementation - // will run as fast as possible, limited only by CPU speed and GPIO time. - #ifdef MICROPY_HW_SOFTSPI_MIN_DELAY - if (delay_half == MICROPY_HW_SOFTSPI_MIN_DELAY) { - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->mosi, (data_out >> 7) & 1); - mp_hal_pin_write(self->sck, 1 - self->polarity); - data_in = (data_in << 1) | mp_hal_pin_read(self->miso); - mp_hal_pin_write(self->sck, self->polarity); - } - if (dest != NULL) { - dest[i] = data_in; - } - } - return; - } - #endif - - for (size_t i = 0; i < len; ++i) { - uint8_t data_out = src[i]; - uint8_t data_in = 0; - for (int j = 0; j < 8; ++j, data_out <<= 1) { - mp_hal_pin_write(self->mosi, (data_out >> 7) & 1); - if (self->phase == 0) { - mp_hal_delay_us_fast(delay_half); - mp_hal_pin_write(self->sck, 1 - self->polarity); - } else { - mp_hal_pin_write(self->sck, 1 - self->polarity); - mp_hal_delay_us_fast(delay_half); - } - data_in = (data_in << 1) | mp_hal_pin_read(self->miso); - if (self->phase == 0) { - mp_hal_delay_us_fast(delay_half); - mp_hal_pin_write(self->sck, self->polarity); - } else { - mp_hal_pin_write(self->sck, self->polarity); - mp_hal_delay_us_fast(delay_half); - } - } - if (dest != NULL) { - dest[i] = data_in; - } - } -} - -const mp_spi_proto_t mp_soft_spi_proto = { - .ioctl = mp_soft_spi_ioctl, - .transfer = mp_soft_spi_transfer, -}; diff --git a/drivers/wiznet5k/README.md b/drivers/wiznet5k/README.md deleted file mode 100644 index 88f25a2b8dbcb..0000000000000 --- a/drivers/wiznet5k/README.md +++ /dev/null @@ -1,6 +0,0 @@ -This is the driver for the WIZnet5x00 series of Ethernet controllers. - -Adapted for MicroPython. - -Original source: https://github.com/Wiznet/W5500_EVB/tree/master/ioLibrary -Taken on: 30 August 2014 diff --git a/drivers/wiznet5k/ethernet/socket.c b/drivers/wiznet5k/ethernet/socket.c deleted file mode 100644 index 7a114aa1bc702..0000000000000 --- a/drivers/wiznet5k/ethernet/socket.c +++ /dev/null @@ -1,718 +0,0 @@ -//***************************************************************************** -// -//! \file socket.c -//! \brief SOCKET APIs Implements file. -//! \details SOCKET APIs like as Berkeley Socket APIs. -//! \version 1.0.3 -//! \date 2013/10/21 -//! \par Revision history -//! <2018/10/09> Nick Moore fixes for CircuitPython -//! <2014/05/01> V1.0.3. Refer to M20140501 -//! 1. Implicit type casting -> Explicit type casting. -//! 2. replace 0x01 with PACK_REMAINED in recvfrom() -//! 3. Validation a destination ip in connect() & sendto(): -//! It occurs a fatal error on converting unint32 address if uint8* addr parameter is not aligned by 4byte address. -//! Copy 4 byte addr value into temporary uint32 variable and then compares it. -//! <2013/12/20> V1.0.2 Refer to M20131220 -//! Remove Warning. -//! <2013/11/04> V1.0.1 2nd Release. Refer to "20131104". -//! In sendto(), Add to clear timeout interrupt status (Sn_IR_TIMEOUT) -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include - -#include "py/mpthread.h" -#include "socket.h" - -#define SOCK_ANY_PORT_NUM 0xC000; - -static uint16_t sock_any_port = SOCK_ANY_PORT_NUM; -static uint16_t sock_io_mode = 0; -static uint16_t sock_is_sending = 0; -static uint16_t sock_remained_size[_WIZCHIP_SOCK_NUM_] = {0,0,}; -static uint8_t sock_pack_info[_WIZCHIP_SOCK_NUM_] = {0,}; - -#if _WIZCHIP_ == 5200 - static uint16_t sock_next_rd[_WIZCHIP_SOCK_NUM_] ={0,}; -#endif - -#define CHECK_SOCKNUM() \ - do{ \ - if(sn > _WIZCHIP_SOCK_NUM_) return SOCKERR_SOCKNUM; \ - }while(0); \ - -#define CHECK_SOCKMODE(mode) \ - do{ \ - if((getSn_MR(sn) & 0x0F) != mode) return SOCKERR_SOCKMODE; \ - }while(0); \ - -#define CHECK_SOCKINIT() \ - do{ \ - if((getSn_SR(sn) != SOCK_INIT)) return SOCKERR_SOCKINIT; \ - }while(0); \ - -#define CHECK_SOCKDATA() \ - do{ \ - if(len == 0) return SOCKERR_DATALEN; \ - }while(0); \ - -void WIZCHIP_EXPORT(socket_reset)(void) { - sock_any_port = SOCK_ANY_PORT_NUM; - sock_io_mode = 0; - sock_is_sending = 0; - /* - memset(sock_remained_size, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); - memset(sock_pack_info, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint8_t)); - */ - -#if _WIZCHIP_ == 5200 - memset(sock_next_rd, 0, _WIZCHIP_SOCK_NUM_ * sizeof(uint16_t)); -#endif -} - -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag) -{ - CHECK_SOCKNUM(); - switch(protocol) - { - case Sn_MR_TCP : - case Sn_MR_UDP : - case Sn_MR_MACRAW : - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW : - case Sn_MR_PPPoE : - break; - #endif - default : - return SOCKERR_SOCKMODE; - } - if((flag & 0x06) != 0) return SOCKERR_SOCKFLAG; -#if _WIZCHIP_ == 5200 - if(flag & 0x10) return SOCKERR_SOCKFLAG; -#endif - - if(flag != 0) - { - switch(protocol) - { - case Sn_MR_TCP: - if((flag & (SF_TCP_NODELAY|SF_IO_NONBLOCK))==0) return SOCKERR_SOCKFLAG; - break; - case Sn_MR_UDP: - if(flag & SF_IGMP_VER2) - { - if((flag & SF_MULTI_ENABLE)==0) return SOCKERR_SOCKFLAG; - } - #if _WIZCHIP_ == 5500 - if(flag & SF_UNI_BLOCK) - { - if((flag & SF_MULTI_ENABLE) == 0) return SOCKERR_SOCKFLAG; - } - #endif - break; - default: - break; - } - } - WIZCHIP_EXPORT(close)(sn); - setSn_MR(sn, (protocol | (flag & 0xF0))); - if(!port) - { - port = sock_any_port++; - if(sock_any_port == 0xFFF0) sock_any_port = SOCK_ANY_PORT_NUM; - } - setSn_PORT(sn,port); - setSn_CR(sn,Sn_CR_OPEN); - while(getSn_CR(sn)); - sock_io_mode |= ((flag & SF_IO_NONBLOCK) << sn); - sock_is_sending &= ~(1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - tmp = getSn_SR(sn); - if ((tmp != SOCK_ESTABLISHED) && (tmp != SOCK_CLOSE_WAIT)) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - } - wiz_send_data(sn, buf, len); - #if _WIZCHIP_ == 5200 - sock_next_rd[sn] = getSn_TX_RD(sn) + len; - #endif - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - sock_is_sending |= (1 << sn); - return len; -} - - -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len) -{ - uint8_t tmp = 0; - uint16_t recvsize = 0; - CHECK_SOCKNUM(); - CHECK_SOCKMODE(Sn_MR_TCP); - CHECK_SOCKDATA(); - - recvsize = getSn_RxMAX(sn); - if(recvsize < len) len = recvsize; - while(1) - { - recvsize = getSn_RX_RSR(sn); - tmp = getSn_SR(sn); - if (tmp != SOCK_ESTABLISHED) - { - if(tmp == SOCK_CLOSE_WAIT) - { - if(recvsize != 0) break; - else if(getSn_TX_FSR(sn) == getSn_TxMAX(sn)) - { - // dpgeorge: Getting here seems to be an orderly shutdown of the - // socket, and trying to get POSIX behaviour we return 0 because: - // "If no messages are available to be received and the peer has per‐ - // formed an orderly shutdown, recv() shall return 0". - // TODO this return value clashes with SOCK_BUSY in non-blocking mode. - WIZCHIP_EXPORT(close)(sn); - return 0; - } - } - else - { - WIZCHIP_EXPORT(close)(sn); - return SOCKERR_SOCKSTATUS; - } - } - if((sock_io_mode & (1< freesize) len = freesize; // check size not to exceed MAX size. - while(1) - { - freesize = getSn_TX_FSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< freesize) ) return SOCK_BUSY; - if(len <= freesize) break; - MICROPY_THREAD_YIELD(); - }; - wiz_send_data(sn, buf, len); - - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR(wizchip_getsubn()); - #endif - - setSn_CR(sn,Sn_CR_SEND); - /* wait to process the command... */ - while(getSn_CR(sn)); - while(1) - { - tmp = getSn_IR(sn); - if(tmp & Sn_IR_SENDOK) - { - setSn_IR(sn, Sn_IR_SENDOK); - break; - } - //M:20131104 - //else if(tmp & Sn_IR_TIMEOUT) return SOCKERR_TIMEOUT; - else if(tmp & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return SOCKERR_TIMEOUT; - } - //////////// - MICROPY_THREAD_YIELD(); - } - #if _WIZCHIP_ == 5200 // for W5200 ARP errata - setSUBR((uint8_t*)"\x00\x00\x00\x00"); - #endif - return len; -} - - - -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port) -{ - uint8_t mr; - uint8_t head[8]; - uint16_t pack_len=0; - - CHECK_SOCKNUM(); - //CHECK_SOCKMODE(Sn_MR_UDP); - switch((mr=getSn_MR(sn)) & 0x0F) - { - case Sn_MR_UDP: - case Sn_MR_MACRAW: - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - case Sn_MR_PPPoE: - break; - #endif - default: - return SOCKERR_SOCKMODE; - } - CHECK_SOCKDATA(); - if(sock_remained_size[sn] == 0) - { - while(1) - { - pack_len = getSn_RX_RSR(sn); - if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED; - if( (sock_io_mode & (1< 1514) - { - WIZCHIP_EXPORT(close)(sn); - return SOCKFATAL_PACKLEN; - } - sock_pack_info[sn] = PACK_FIRST; - } - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn,buf,pack_len); - break; - #if ( _WIZCHIP_ < 5200 ) - case Sn_MR_IPRAW: - if(sock_remained_size[sn] == 0) - { - wiz_recv_data(sn, head, 6); - setSn_CR(sn,Sn_CR_RECV); - while(getSn_CR(sn)); - addr[0] = head[0]; - addr[1] = head[1]; - addr[2] = head[2]; - addr[3] = head[3]; - sock_remained_size[sn] = head[4]; - sock_remaiend_size[sn] = (sock_remained_size[sn] << 8) + head[5]; - sock_pack_info[sn] = PACK_FIRST; - } - // - // Need to packet length check - // - if(len < sock_remained_size[sn]) pack_len = len; - else pack_len = sock_remained_size[sn]; - wiz_recv_data(sn, buf, pack_len); // data copy. - break; - #endif - default: - wiz_recv_ignore(sn, pack_len); // data copy. - sock_remained_size[sn] = pack_len; - break; - } - setSn_CR(sn,Sn_CR_RECV); - /* wait to process the command... */ - while(getSn_CR(sn)) ; - sock_remained_size[sn] -= pack_len; - //M20140501 : replace 0x01 with PACK_REMAINED - //if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= 0x01; - if(sock_remained_size[sn] != 0) sock_pack_info[sn] |= PACK_REMAINED; - // - return pack_len; -} - - -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg) -{ - uint8_t tmp = 0; - CHECK_SOCKNUM(); - switch(cstype) - { - case CS_SET_IOMODE: - tmp = *((uint8_t*)arg); - if(tmp == SOCK_IO_NONBLOCK) sock_io_mode |= (1< explict type casting - //*((uint8_t*)arg) = (sock_io_mode >> sn) & 0x0001; - *((uint8_t*)arg) = (uint8_t)((sock_io_mode >> sn) & 0x0001); - // - break; - case CS_GET_MAXTXBUF: - *((uint16_t*)arg) = getSn_TxMAX(sn); - break; - case CS_GET_MAXRXBUF: - *((uint16_t*)arg) = getSn_RxMAX(sn); - break; - case CS_CLR_INTERRUPT: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTERRUPT: - *((uint8_t*)arg) = getSn_IR(sn); - break; - case CS_SET_INTMASK: - if( (*(uint8_t*)arg) > SIK_ALL) return SOCKERR_ARG; - setSn_IMR(sn,*(uint8_t*)arg); - break; - case CS_GET_INTMASK: - *((uint8_t*)arg) = getSn_IMR(sn); - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - // M20131220 : Remove warning - //uint8_t tmp; - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_TTL: - setSn_TTL(sn,*(uint8_t*)arg); - break; - case SO_TOS: - setSn_TOS(sn,*(uint8_t*)arg); - break; - case SO_MSS: - setSn_MSSR(sn,*(uint16_t*)arg); - break; - case SO_DESTIP: - setSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - setSn_DPORT(sn, *(uint16_t*)arg); - break; -#if _WIZCHIP_ != 5100 - case SO_KEEPALIVESEND: - CHECK_SOCKMODE(Sn_MR_TCP); - #if _WIZCHIP_ > 5200 - if(getSn_KPALVTR(sn) != 0) return SOCKERR_SOCKOPT; - #endif - setSn_CR(sn,Sn_CR_SEND_KEEP); - while(getSn_CR(sn) != 0) - { - // M20131220 - //if ((tmp = getSn_IR(sn)) & Sn_IR_TIMEOUT) - if (getSn_IR(sn) & Sn_IR_TIMEOUT) - { - setSn_IR(sn, Sn_IR_TIMEOUT); - return SOCKERR_TIMEOUT; - } - } - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - setSn_KPALVTR(sn,*(uint8_t*)arg); - break; - #endif -#endif - default: - return SOCKERR_ARG; - } - return SOCK_OK; -} - -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg) -{ - CHECK_SOCKNUM(); - switch(sotype) - { - case SO_FLAG: - *(uint8_t*)arg = getSn_MR(sn) & 0xF0; - break; - case SO_TTL: - *(uint8_t*) arg = getSn_TTL(sn); - break; - case SO_TOS: - *(uint8_t*) arg = getSn_TOS(sn); - break; - case SO_MSS: - *(uint8_t*) arg = getSn_MSSR(sn); - case SO_DESTIP: - getSn_DIPR(sn, (uint8_t*)arg); - break; - case SO_DESTPORT: - *(uint16_t*) arg = getSn_DPORT(sn); - break; - #if _WIZCHIP_ > 5200 - case SO_KEEPALIVEAUTO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint16_t*) arg = getSn_KPALVTR(sn); - break; - #endif - case SO_SENDBUF: - *(uint16_t*) arg = getSn_TX_FSR(sn); - case SO_RECVBUF: - *(uint16_t*) arg = getSn_RX_RSR(sn); - case SO_STATUS: - *(uint8_t*) arg = getSn_SR(sn); - break; - case SO_REMAINSIZE: - if(getSn_MR(sn) == Sn_MR_TCP) - *(uint16_t*)arg = getSn_RX_RSR(sn); - else - *(uint16_t*)arg = sock_remained_size[sn]; - break; - case SO_PACKINFO: - CHECK_SOCKMODE(Sn_MR_TCP); - *(uint8_t*)arg = sock_pack_info[sn]; - break; - default: - return SOCKERR_SOCKOPT; - } - return SOCK_OK; -} diff --git a/drivers/wiznet5k/ethernet/socket.h b/drivers/wiznet5k/ethernet/socket.h deleted file mode 100644 index 4f602e429c7be..0000000000000 --- a/drivers/wiznet5k/ethernet/socket.h +++ /dev/null @@ -1,472 +0,0 @@ -//***************************************************************************** -// -//! \file socket.h -//! \brief SOCKET APIs Header file. -//! \details SOCKET APIs like as berkeley socket api. -//! \version 1.0.2 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2. Refer to M20140501 -//! 1. Modify the comment : SO_REMAINED -> PACK_REMAINED -//! 2. Add the comment as zero byte udp data reception in getsockopt(). -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -/** - * @defgroup WIZnet_socket_APIs 1. WIZnet socket APIs - * @brief WIZnet socket APIs are based on Berkeley socket APIs, thus it has much similar name and interface. - * But there is a little bit of difference. - * @details - * Comparison between WIZnet and Berkeley SOCKET APIs - * - * - * - * - * - * - * - * - * - * - * - * - *
API WIZnet Berkeley
socket() O O
bind() X O
listen() O O
connect() O O
accept() X O
recv() O O
send() O O
recvfrom() O O
sendto() O O
closesocket() O
close() & disconnect()
O
- * There are @b bind() and @b accept() functions in @b Berkeley SOCKET API but, - * not in @b WIZnet SOCKET API. Because socket() of WIZnet is not only creating a SOCKET but also binding a local port number, - * and listen() of WIZnet is not only listening to connection request from client but also accepting the connection request. \n - * When you program "TCP SERVER" with Berkeley SOCKET API, you can use only one listen port. - * When the listen SOCKET accepts a connection request from a client, it keeps listening. - * After accepting the connection request, a new SOCKET is created and the new SOCKET is used in communication with the client. \n - * Following figure shows network flow diagram by Berkeley SOCKET API. - * @image html Berkeley_SOCKET.jpg "" - * But, When you program "TCP SERVER" with WIZnet SOCKET API, you can use as many as 8 listen SOCKET with same port number. \n - * Because there's no accept() in WIZnet SOCKET APIs, when the listen SOCKET accepts a connection request from a client, - * it is changed in order to communicate with the client. - * And the changed SOCKET is not listening any more and is dedicated for communicating with the client. \n - * If there're many listen SOCKET with same listen port number and a client requests a connection, - * the SOCKET which has the smallest SOCKET number accepts the request and is changed as communication SOCKET. \n - * Following figure shows network flow diagram by WIZnet SOCKET API. - * @image html WIZnet_SOCKET.jpg "" - */ -#ifndef _WIZCHIP_SOCKET_H_ -#define _WIZCHIP_SOCKET_H_ - -// use this macro for exported names to avoid name clashes -#define WIZCHIP_EXPORT(name) wizchip_ ## name - -#include "wizchip_conf.h" - -#define SOCKET uint8_t ///< SOCKET type define for legacy driver - -#define SOCK_OK 1 ///< Result is OK about socket process. -#define SOCK_BUSY 0 ///< Socket is busy on processing the operation. Valid only Non-block IO Mode. -#define SOCK_FATAL -1000 ///< Result is fatal error about socket process. - -#define SOCK_ERROR 0 -#define SOCKERR_SOCKNUM (SOCK_ERROR - 1) ///< Invalid socket number -#define SOCKERR_SOCKOPT (SOCK_ERROR - 2) ///< Invalid socket option -#define SOCKERR_SOCKINIT (SOCK_ERROR - 3) ///< Socket is not initialized -#define SOCKERR_SOCKCLOSED (SOCK_ERROR - 4) ///< Socket unexpectedly closed. -#define SOCKERR_SOCKMODE (SOCK_ERROR - 5) ///< Invalid socket mode for socket operation. -#define SOCKERR_SOCKFLAG (SOCK_ERROR - 6) ///< Invalid socket flag -#define SOCKERR_SOCKSTATUS (SOCK_ERROR - 7) ///< Invalid socket status for socket operation. -#define SOCKERR_ARG (SOCK_ERROR - 10) ///< Invalid argument. -#define SOCKERR_PORTZERO (SOCK_ERROR - 11) ///< Port number is zero -#define SOCKERR_IPINVALID (SOCK_ERROR - 12) ///< Invalid IP address -#define SOCKERR_TIMEOUT (SOCK_ERROR - 13) ///< Timeout occurred -#define SOCKERR_DATALEN (SOCK_ERROR - 14) ///< Data length is zero or greater than buffer max size. -#define SOCKERR_BUFFER (SOCK_ERROR - 15) ///< Socket buffer is not enough for data communication. - -#define SOCKFATAL_PACKLEN (SOCK_FATAL - 1) ///< Invalid packet length. Fatal Error. - -/* - * SOCKET FLAG - */ -#define SF_ETHER_OWN (Sn_MR_MFEN) ///< In \ref Sn_MR_MACRAW, Receive only the packet as broadcast, multicast and own packet -#define SF_IGMP_VER2 (Sn_MR_MC) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE, Select IGMP version 2. -#define SF_TCP_NODELAY (Sn_MR_ND) ///< In \ref Sn_MR_TCP, Use to nodelayed ack. -#define SF_MULTI_ENABLE (Sn_MR_MULTI) ///< In \ref Sn_MR_UDP, Enable multicast mode. - -#if _WIZCHIP_ == 5500 - #define SF_BROAD_BLOCK (Sn_MR_BCASTB) ///< In \ref Sn_MR_UDP or \ref Sn_MR_MACRAW, Block broadcast packet. Valid only in W5500 - #define SF_MULTI_BLOCK (Sn_MR_MMB) ///< In \ref Sn_MR_MACRAW, Block multicast packet. Valid only in W5500 - #define SF_IPv6_BLOCK (Sn_MR_MIP6B) ///< In \ref Sn_MR_MACRAW, Block IPv6 packet. Valid only in W5500 - #define SF_UNI_BLOCK (Sn_MR_UCASTB) ///< In \ref Sn_MR_UDP with \ref SF_MULTI_ENABLE. Valid only in W5500 -#endif - -#define SF_IO_NONBLOCK 0x01 ///< Socket nonblock io mode. It used parameter in \ref socket(). - -/* - * UDP & MACRAW Packet Infomation - */ -#define PACK_FIRST 0x80 ///< In Non-TCP packet, It indicates to start receiving a packet. -#define PACK_REMAINED 0x01 ///< In Non-TCP packet, It indicates to remain a packet to be received. -#define PACK_COMPLETED 0x00 ///< In Non-TCP packet, It indicates to complete to receive a packet. - -// resets all global state associated with the socket interface -void WIZCHIP_EXPORT(socket_reset)(void); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Open a socket. - * @details Initializes the socket with 'sn' passed as parameter and open. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param protocol Protocol type to operate such as TCP, UDP and MACRAW. - * @param port Port number to be bined. - * @param flag Socket flags as \ref SF_ETHER_OWN, \ref SF_IGMP_VER2, \ref SF_TCP_NODELAY, \ref SF_MULTI_ENABLE, \ref SF_IO_NONBLOCK and so on.\n - * Valid flags only in W5500 : @ref SF_BROAD_BLOCK, @ref SF_MULTI_BLOCK, @ref SF_IPv6_BLOCK, and @ref SF_UNI_BLOCK. - * @sa Sn_MR - * - * @return @b Success : The socket number @b 'sn' passed as parameter\n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Not support socket mode as TCP, UDP, and so on. \n - * @ref SOCKERR_SOCKFLAG - Invaild socket flag. - */ -int8_t WIZCHIP_EXPORT(socket)(uint8_t sn, uint8_t protocol, uint16_t port, uint8_t flag); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Close a socket. - * @details It closes the socket with @b'sn' passed as parameter. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail : @ref SOCKERR_SOCKNUM - Invalid socket number - */ -int8_t WIZCHIP_EXPORT(close)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Listen to a connection request from a client. - * @details It is listening to a connection request from a client. - * If connection request is accepted successfully, the connection is established. Socket sn is used in passive(server) mode. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKINIT - Socket is not initialized \n - * @ref SOCKERR_SOCKCLOSED - Socket closed unexpectedly. - */ -int8_t WIZCHIP_EXPORT(listen)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to connect a server. - * @details It requests connection to the server with destination IP address and port number passed as parameter.\n - * @note It is valid only in TCP client mode. - * In block io mode, it does not return until connection is completed. - * In Non-block io mode, it return @ref SOCK_BUSY immediately. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number\n - * @ref SOCKERR_SOCKMODE - Invalid socket mode\n - * @ref SOCKERR_SOCKINIT - Socket is not initialized\n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_TIMEOUT - Timeout occurred during request connection\n - * @ref SOCK_BUSY - In non-block io mode, it returned immediately\n - */ -int8_t WIZCHIP_EXPORT(connect)(uint8_t sn, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Try to disconnect a connection socket. - * @details It sends request message to disconnect the TCP socket 'sn' passed as parameter to the server or client. - * @note It is valid only in TCP server or client mode. \n - * In block io mode, it does not return until disconnection is completed. \n - * In Non-block io mode, it return @ref SOCK_BUSY immediately. \n - - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @return @b Success : @ref SOCK_OK \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int8_t WIZCHIP_EXPORT(disconnect)(uint8_t sn); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Send data to the connected peer in TCP socket. - * @details It is used to send outgoing data to the connected socket. - * @note It is valid only in TCP server or client mode. It can't send data greater than socket buffer size. \n - * In block io mode, It doesn't return until data send is completed - socket buffer size is greater than data. \n - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. \n - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer containing data to be sent. - * @param len The byte length of data in buf. - * @return @b Success : The sent data size \n - * @b Fail : \n @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(send)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive data from the connected peer. - * @details It is used to read incoming data from the connected socket.\n - * It waits for data as much as the application wants to receive. - * @note It is valid only in TCP server or client mode. It can't receive data greater than socket buffer size. \n - * In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer. \n - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. \n - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * @return @b Success : The real received data size \n - * @b Fail :\n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Sends datagram to the peer with destination IP address and port number passed as parameter. - * @details It sends datagram of UDP or MACRAW to the peer with destination IP address and port number passed as parameter.\n - * Even if the connectionless socket has been previously connected to a specific address, - * the address and port number parameters override the destination address for that particular datagram only. - * @note In block io mode, It doesn't return until data send is completed - socket buffer size is greater than len. - * In non-block io mode, It return @ref SOCK_BUSY immediately when socket buffer is not enough. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to send outgoing data. - * @param len The byte length of data in buf. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * @param port Destination port number. - * - * @return @b Success : The sent data size \n - * @b Fail :\n @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKSTATUS - Invalid socket status for socket operation \n - * @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_IPINVALID - Wrong server IP address\n - * @ref SOCKERR_PORTZERO - Server port zero\n - * @ref SOCKERR_SOCKCLOSED - Socket unexpectedly closed \n - * @ref SOCKERR_TIMEOUT - Timeout occurred \n - * @ref SOCK_BUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(sendto)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); - -/** - * @ingroup WIZnet_socket_APIs - * @brief Receive datagram of UDP or MACRAW - * @details This function is an application I/F function which is used to receive the data in other then TCP mode. \n - * This function is used to receive UDP and MAC_RAW mode, and handle the header as well. - * This function can divide to received the packet data. - * On the MACRAW SOCKET, the addr and port parameters are ignored. - * @note In block io mode, it doesn't return until data reception is completed - data is filled as len in socket buffer - * In non-block io mode, it return @ref SOCK_BUSY immediately when len is greater than data size in socket buffer. - * - * @param sn Socket number. It should be 0 ~ @ref \_WIZCHIP_SOCK_NUM_. - * @param buf Pointer buffer to read incoming data. - * @param len The max data length of data in buf. - * When the received packet size <= len, receives data as packet sized. - * When others, receives data as len. - * @param addr Pointer variable of destination IP address. It should be allocated 4 bytes. - * It is valid only when the first call recvfrom for receiving the packet. - * When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * @param port Pointer variable of destination port number. - * It is valid only when the first call recvform for receiving the packet. -* When it is valid, @ref packinfo[7] should be set as '1' after call @ref getsockopt(sn, SO_PACKINFO, &packinfo). - * - * @return @b Success : This function return real received data size for success.\n - * @b Fail : @ref SOCKERR_DATALEN - zero data length \n - * @ref SOCKERR_SOCKMODE - Invalid operation in the socket \n - * @ref SOCKERR_SOCKNUM - Invalid socket number \n - * @ref SOCKBUSY - Socket is busy. - */ -int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); - - -///////////////////////////// -// SOCKET CONTROL & OPTION // -///////////////////////////// -#define SOCK_IO_BLOCK 0 ///< Socket Block IO Mode in @ref setsockopt(). -#define SOCK_IO_NONBLOCK 1 ///< Socket Non-block IO Mode in @ref setsockopt(). - -/** - * @defgroup DATA_TYPE DATA TYPE - */ - -/** - * @ingroup DATA_TYPE - * @brief The kind of Socket Interrupt. - * @sa Sn_IR, Sn_IMR, setSn_IR(), getSn_IR(), setSn_IMR(), getSn_IMR() - */ -typedef enum -{ - SIK_CONNECTED = (1 << 0), ///< connected - SIK_DISCONNECTED = (1 << 1), ///< disconnected - SIK_RECEIVED = (1 << 2), ///< data received - SIK_TIMEOUT = (1 << 3), ///< timeout occurred - SIK_SENT = (1 << 4), ///< send ok - SIK_ALL = 0x1F, ///< all interrupt -}sockint_kind; - -/** - * @ingroup DATA_TYPE - * @brief The type of @ref ctlsocket(). - */ -typedef enum -{ - CS_SET_IOMODE, ///< set socket IO mode with @ref SOCK_IO_BLOCK or @ref SOCK_IO_NONBLOCK - CS_GET_IOMODE, ///< get socket IO mode - CS_GET_MAXTXBUF, ///< get the size of socket buffer allocated in TX memory - CS_GET_MAXRXBUF, ///< get the size of socket buffer allocated in RX memory - CS_CLR_INTERRUPT, ///< clear the interrupt of socket with @ref sockint_kind - CS_GET_INTERRUPT, ///< get the socket interrupt. refer to @ref sockint_kind - CS_SET_INTMASK, ///< set the interrupt mask of socket with @ref sockint_kind - CS_GET_INTMASK ///< get the masked interrupt of socket. refer to @ref sockint_kind -}ctlsock_type; - - -/** - * @ingroup DATA_TYPE - * @brief The type of socket option in @ref setsockopt() or @ref getsockopt() - */ -typedef enum -{ - SO_FLAG, ///< Valid only in getsockopt(), For set flag of socket refer to flag in @ref socket(). - SO_TTL, ///< Set/Get TTL. @ref Sn_TTL ( @ref setSn_TTL(), @ref getSn_TTL() ) - SO_TOS, ///< Set/Get TOS. @ref Sn_TOS ( @ref setSn_TOS(), @ref getSn_TOS() ) - SO_MSS, ///< Set/Get MSS. @ref Sn_MSSR ( @ref setSn_MSSR(), @ref getSn_MSSR() ) - SO_DESTIP, ///< Set/Get the destination IP address. @ref Sn_DIPR ( @ref setSn_DIPR(), @ref getSn_DIPR() ) - SO_DESTPORT, ///< Set/Get the destination Port number. @ref Sn_DPORT ( @ref setSn_DPORT(), @ref getSn_DPORT() ) -#if _WIZCHIP_ != 5100 - SO_KEEPALIVESEND, ///< Valid only in setsockopt. Manually send keep-alive packet in TCP mode - #if _WIZCHIP_ > 5200 - SO_KEEPALIVEAUTO, ///< Set/Get keep-alive auto transmission timer in TCP mode - #endif -#endif - SO_SENDBUF, ///< Valid only in getsockopt. Get the free data size of Socekt TX buffer. @ref Sn_TX_FSR, @ref getSn_TX_FSR() - SO_RECVBUF, ///< Valid only in getsockopt. Get the received data size in socket RX buffer. @ref Sn_RX_RSR, @ref getSn_RX_RSR() - SO_STATUS, ///< Valid only in getsockopt. Get the socket status. @ref Sn_SR, @ref getSn_SR() - SO_REMAINSIZE, ///< Valid only in getsockopt. Get the remained packet size in other then TCP mode. - SO_PACKINFO ///< Valid only in getsockopt. Get the packet information as @ref PACK_FIRST, @ref PACK_REMAINED, and @ref PACK_COMPLETED in other then TCP mode. -}sockopt_type; - -/** - * @ingroup WIZnet_socket_APIs - * @brief Control socket. - * @details Control IO mode, Interrupt & Mask of socket and get the socket buffer information. - * Refer to @ref ctlsock_type. - * @param sn socket number - * @param cstype type of control socket. refer to @ref ctlsock_type. - * @param arg Data type and value is determined according to @ref ctlsock_type. \n - * - * - * - * - * - *
@b cstype @b data type@b value
@ref CS_SET_IOMODE \n @ref CS_GET_IOMODE uint8_t @ref SOCK_IO_BLOCK @ref SOCK_IO_NONBLOCK
@ref CS_GET_MAXTXBUF \n @ref CS_GET_MAXRXBUF uint16_t 0 ~ 16K
@ref CS_CLR_INTERRUPT \n @ref CS_GET_INTERRUPT \n @ref CS_SET_INTMASK \n @ref CS_GET_INTMASK @ref sockint_kind @ref SIK_CONNECTED, etc.
- * @return @b Success @ref SOCK_OK \n - * @b fail @ref SOCKERR_ARG - Invalid argument\n - */ -int8_t WIZCHIP_EXPORT(ctlsocket)(uint8_t sn, ctlsock_type cstype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief set socket options - * @details Set socket option like as TTL, MSS, TOS, and so on. Refer to @ref sockopt_type. - * - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_TTL uint8_t 0 ~ 255
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t 0 ~ 65535
@ref SO_KEEPALIVESEND null null
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_TIMEOUT - Timeout occurred when sending keep-alive packet \n - */ -int8_t WIZCHIP_EXPORT(setsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -/** - * @ingroup WIZnet_socket_APIs - * @brief get socket options - * @details Get socket option like as FLAG, TTL, MSS, and so on. Refer to @ref sockopt_type - * @param sn socket number - * @param sotype socket option type. refer to @ref sockopt_type - * @param arg Data type and value is determined according to sotype. \n - * - * - * - * - * - * - * - * - * - * - * - * - * - *
@b sotype @b data type@b value
@ref SO_FLAG uint8_t @ref SF_ETHER_OWN, etc...
@ref SO_TOS uint8_t 0 ~ 255
@ref SO_MSS uint16_t 0 ~ 65535
@ref SO_DESTIP uint8_t[4]
@ref SO_DESTPORT uint16_t
@ref SO_KEEPALIVEAUTO uint8_t 0 ~ 255
@ref SO_SENDBUF uint16_t 0 ~ 65535
@ref SO_RECVBUF uint16_t 0 ~ 65535
@ref SO_STATUS uint8_t @ref SOCK_ESTABLISHED, etc..
@ref SO_REMAINSIZE uint16_t 0~ 65535
@ref SO_PACKINFO uint8_t @ref PACK_FIRST, etc...
- * @return - * - @b Success : @ref SOCK_OK \n - * - @b Fail - * - @ref SOCKERR_SOCKNUM - Invalid Socket number \n - * - @ref SOCKERR_SOCKOPT - Invalid socket option or its value \n - * - @ref SOCKERR_SOCKMODE - Invalid socket mode \n - * @note - * The option as PACK_REMAINED and SO_PACKINFO is valid only in NON-TCP mode and after call @ref recvfrom(). \n - * When SO_PACKINFO value is PACK_FIRST and the return value of recvfrom() is zero, - * This means the zero byte UDP data(UDP Header only) received. - */ -int8_t WIZCHIP_EXPORT(getsockopt)(uint8_t sn, sockopt_type sotype, void* arg); - -#endif // _WIZCHIP_SOCKET_H_ diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.c b/drivers/wiznet5k/ethernet/w5200/w5200.c deleted file mode 100644 index cbcb136091124..0000000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.c +++ /dev/null @@ -1,206 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.c and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include "w5200.h" - -#define SMASK (0x7ff) /* tx buffer mask */ -#define RMASK (0x7ff) /* rx buffer mask */ -#define SSIZE (2048) /* max tx buffer size */ -#define RSIZE (2048) /* max rx buffer size */ - -#define TXBUF_BASE (0x8000) -#define RXBUF_BASE (0xc000) -#define SBASE(sn) (TXBUF_BASE + SSIZE * (sn)) /* tx buffer base for socket sn */ -#define RBASE(sn) (RXBUF_BASE + RSIZE * (sn)) /* rx buffer base for socket sn */ - -uint8_t WIZCHIP_READ(uint32_t AddrSel) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00, - 0x01, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - uint8_t ret; - WIZCHIP.IF.SPI._read_bytes(&ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[5] = { - AddrSel >> 8, - AddrSel, - 0x80, - 0x01, - wb, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 5); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x00 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._read_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) { - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - uint8_t spi_data[4] = { - AddrSel >> 8, - AddrSel, - 0x80 | ((len >> 8) & 0x7f), - len & 0xff, - }; - WIZCHIP.IF.SPI._write_bytes(spi_data, 4); - WIZCHIP.IF.SPI._write_bytes(pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -uint16_t getSn_TX_FSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_TX_FSR(sn)) << 8) | WIZCHIP_READ(Sn_TX_FSR(sn) + 1); - } - } while (val != val1); - return val; -} - -uint16_t getSn_RX_RSR(uint8_t sn) { - uint16_t val = 0, val1 = 0; - do { - val1 = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - if (val1 != 0) { - val = (WIZCHIP_READ(Sn_RX_RSR(sn)) << 8) | WIZCHIP_READ(Sn_RX_RSR(sn) + 1); - } - } while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_TX_WR(sn); - uint16_t offset = ptr & SMASK; - uint32_t addr = offset + SBASE(sn); - - if (offset + len > SSIZE) { - // implement wrap-around circular buffer - uint16_t size = SSIZE - offset; - WIZCHIP_WRITE_BUF(addr, wizdata, size); - WIZCHIP_WRITE_BUF(SBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_WRITE_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_TX_WR(sn, ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) { - if (len == 0) { - return; - } - - uint16_t ptr = getSn_RX_RD(sn); - uint16_t offset = ptr & RMASK; - uint16_t addr = RBASE(sn) + offset; - - if (offset + len > RSIZE) { - // implement wrap-around circular buffer - uint16_t size = RSIZE - offset; - WIZCHIP_READ_BUF(addr, wizdata, size); - WIZCHIP_READ_BUF(RBASE(sn), wizdata + size, len - size); - } else { - WIZCHIP_READ_BUF(addr, wizdata, len); - } - - ptr += len; - setSn_RX_RD(sn, ptr); -} - -void wiz_recv_ignore(uint8_t sn, uint16_t len) { - uint16_t ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn, ptr); -} diff --git a/drivers/wiznet5k/ethernet/w5200/w5200.h b/drivers/wiznet5k/ethernet/w5200/w5200.h deleted file mode 100644 index 988c8827fc616..0000000000000 --- a/drivers/wiznet5k/ethernet/w5200/w5200.h +++ /dev/null @@ -1,2092 +0,0 @@ -// dpgeorge: this file taken from w5500/w5500.h and adapted to W5200 - -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5200_H_ -#define _W5200_H_ - -#include -#include "../wizchip_conf.h" -//#include "board.h" - -#define _W5200_IO_BASE_ 0x00000000 - -#define WIZCHIP_CREG_ADDR(addr) (_W5200_IO_BASE_ + (addr)) - -#define WIZCHIP_CH_BASE (0x4000) -#define WIZCHIP_CH_SIZE (0x100) -#define WIZCHIP_SREG_ADDR(sn, addr) (_W5200_IO_BASE_ + WIZCHIP_CH_BASE + (sn) * WIZCHIP_CH_SIZE + (addr)) - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR WIZCHIP_CREG_ADDR(0x0000) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR WIZCHIP_CREG_ADDR(0x0001) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR WIZCHIP_CREG_ADDR(0x0005) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR WIZCHIP_CREG_ADDR(0x0009) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR WIZCHIP_CREG_ADDR(0x000f) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -//#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR WIZCHIP_CREG_ADDR(0x0015) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR WIZCHIP_CREG_ADDR(0x0016) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -//#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -//#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR WIZCHIP_CREG_ADDR(0x0017) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR WIZCHIP_CREG_ADDR(0x0019) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER WIZCHIP_CREG_ADDR(0x0028) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC WIZCHIP_CREG_ADDR(0x0029) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -//#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -//#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -//#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -//#define UIPR (_W5500_IO_BASE_ + (0x002a << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -//#define UPORTR (_W5500_IO_BASE_ + (0x002e << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -//#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) -#define PHYSTATUS WIZCHIP_CREG_ADDR(0x0035) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -//#define VERSIONR (_W5200_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) WIZCHIP_SREG_ADDR(N, 0x0000) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) WIZCHIP_SREG_ADDR(N, 0x0001) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) WIZCHIP_SREG_ADDR(N, 0x0002) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) WIZCHIP_SREG_ADDR(N, 0x0003) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) WIZCHIP_SREG_ADDR(N, 0x0004) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) WIZCHIP_SREG_ADDR(N, 0x0006) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) WIZCHIP_SREG_ADDR(N, 0x000c) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) WIZCHIP_SREG_ADDR(N, 0x0010) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) WIZCHIP_SREG_ADDR(N, 0x0012) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) WIZCHIP_SREG_ADDR(N, 0x0015) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) WIZCHIP_SREG_ADDR(N, 0x0016) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001e) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) WIZCHIP_SREG_ADDR(N, 0x001f) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) WIZCHIP_SREG_ADDR(N, 0x0020) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0022) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) WIZCHIP_SREG_ADDR(N, 0x0024) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) WIZCHIP_SREG_ADDR(N, 0x0026) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) WIZCHIP_SREG_ADDR(N, 0x0028) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) WIZCHIP_SREG_ADDR(N, 0x002a) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -//#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -//#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -//#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -// PHYSTATUS register -#define PHYSTATUS_POWERDOWN (0x08) -#define PHYSTATUS_LINK (0x20) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -//#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -//#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -// dpgeorge: not yet implemented -#define setINTLEVEL(intlevel) (void)intlevel -#if 0 -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } -#endif - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -// dpgeorge: not yet implemented -#define getINTLEVEL() (0) -#if 0 -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -// dpgeorge: not yet implemented -#define setSIR(sir) ((void)sir) -#if 0 -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -// dpgeorge: not yet implemented -#define getSIR() (0) -#if 0 -#define getSIR() \ - WIZCHIP_READ(SIR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -// dpgeorge: not yet implemented -#define setSIMR(simr) ((void)simr) -#if 0 -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -// dpgeorge: not yet implemented -#define getSIMR() (0) -#if 0 -#define getSIMR() \ - WIZCHIP_READ(SIMR) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(RTR + 1, (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(RTR + 1)) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#if 0 -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) -#endif - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYSTATUS() \ - WIZCHIP_READ(PHYSTATUS) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -/* -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - */ -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -// dpgeorge: not yet implemented -#define setSn_IMR(sn, imr) (void)sn; (void)imr -#if 0 -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -// dpgeorge: not yet implemented -#define getSn_IMR(sn) (0) -#if 0 -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) -#endif - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(Sn_PORT(sn) + 1, (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) | WIZCHIP_READ(Sn_PORT(sn) + 1)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(Sn_DPORT(sn) + 1, (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ((Sn_DPORT(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE((Sn_MSSR(sn)+1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ((Sn_MSSR(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ((Sn_TX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE((Sn_TX_WR(sn)+1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ((Sn_TX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE((Sn_RX_RD(sn)+1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ((Sn_RX_RD(sn)+1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ((Sn_RX_WR(sn)+1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#if 0 // dpgeorge -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// -#endif - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -void wiz_init(void); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.c b/drivers/wiznet5k/ethernet/w5500/w5500.c deleted file mode 100644 index fef08e2e3e158..0000000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.c +++ /dev/null @@ -1,246 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.c -//! \brief W5500 HAL Interface. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.2 -//! 1. Implicit type casting -> Explicit type casting. Refer to M20140501 -//! Fixed the problem on porting into under 32bit MCU -//! Issued by Mathias ClauBen, wizwiki forum ID Think01 and bobh -//! Thank for your interesting and serious advices. -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.0.1 -//! 1. Remove warning -//! 2. WIZCHIP_READ_BUF WIZCHIP_WRITE_BUF in case _WIZCHIP_IO_MODE_SPI_FDM_ -//! for loop optimized(removed). refer to M20131220 -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -//#include -#include "w5500.h" - -#define _W5500_SPI_VDM_OP_ 0x00 -#define _W5500_SPI_FDM_OP_LEN1_ 0x01 -#define _W5500_SPI_FDM_OP_LEN2_ 0x02 -#define _W5500_SPI_FDM_OP_LEN4_ 0x03 - -//////////////////////////////////////////////////// - -#define LPC_SSP0 (0) - -static void Chip_SSP_ReadFrames_Blocking(int dummy, uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._read_bytes(buf, len); -} - -static void Chip_SSP_WriteFrames_Blocking(int dummy, const uint8_t *buf, uint32_t len) { - WIZCHIP.IF.SPI._write_bytes(buf, len); -} - -uint8_t WIZCHIP_READ(uint32_t AddrSel) -{ - uint8_t ret; - uint8_t spi_data[3]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //ret = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, &ret, 1); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); - return ret; -} - -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ) -{ - uint8_t spi_data[4]; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //WIZCHIP.IF.SPI._write_byte(wb); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - spi_data[3] = wb; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 4); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_READ_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // pBuf[i] = WIZCHIP.IF.SPI._read_byte(); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_ReadFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len) -{ - uint8_t spi_data[3]; - //uint16_t i; - - WIZCHIP_CRITICAL_ENTER(); - WIZCHIP.CS._select(); - - AddrSel |= (_W5500_SPI_WRITE_ | _W5500_SPI_VDM_OP_); - - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x00FF0000) >> 16); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x0000FF00) >> 8); - //WIZCHIP.IF.SPI._write_byte((AddrSel & 0x000000FF) >> 0); - //for(i = 0; i < len; i++) - // WIZCHIP.IF.SPI._write_byte(pBuf[i]); - spi_data[0] = (AddrSel & 0x00FF0000) >> 16; - spi_data[1] = (AddrSel & 0x0000FF00) >> 8; - spi_data[2] = (AddrSel & 0x000000FF) >> 0; - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, spi_data, 3); - Chip_SSP_WriteFrames_Blocking(LPC_SSP0, pBuf, len); - - WIZCHIP.CS._deselect(); - WIZCHIP_CRITICAL_EXIT(); -} - - -uint16_t getSn_TX_FSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_TX_FSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_TX_FSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_FSR(sn),1)); - } - }while (val != val1); - return val; -} - - -uint16_t getSn_RX_RSR(uint8_t sn) -{ - uint16_t val=0,val1=0; - - do - { - val1 = WIZCHIP_READ(Sn_RX_RSR(sn)); - val1 = (val1 << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - if (val1 != 0) - { - val = WIZCHIP_READ(Sn_RX_RSR(sn)); - val = (val << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RSR(sn),1)); - } - }while (val != val1); - return val; -} - -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_TX_WR(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = (ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_TXBUF_BLOCK(sn) << 3); - // - WIZCHIP_WRITE_BUF(addrsel,wizdata, len); - - ptr += len; - setSn_TX_WR(sn,ptr); -} - -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len) -{ - uint16_t ptr = 0; - uint32_t addrsel = 0; - - if(len == 0) return; - ptr = getSn_RX_RD(sn); - //M20140501 : implict type casting -> explict type casting - //addrsel = ((ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - addrsel = ((uint32_t)ptr << 8) + (WIZCHIP_RXBUF_BLOCK(sn) << 3); - // - WIZCHIP_READ_BUF(addrsel, wizdata, len); - ptr += len; - - setSn_RX_RD(sn,ptr); -} - - -void wiz_recv_ignore(uint8_t sn, uint16_t len) -{ - uint16_t ptr = 0; - - ptr = getSn_RX_RD(sn); - ptr += len; - setSn_RX_RD(sn,ptr); -} diff --git a/drivers/wiznet5k/ethernet/w5500/w5500.h b/drivers/wiznet5k/ethernet/w5500/w5500.h deleted file mode 100644 index f94eed3aff7fe..0000000000000 --- a/drivers/wiznet5k/ethernet/w5500/w5500.h +++ /dev/null @@ -1,2057 +0,0 @@ -//***************************************************************************** -// -//! \file w5500.h -//! \brief W5500 HAL Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _W5500_H_ -#define _W5500_H_ - -#include -#include "../wizchip_conf.h" - -#define _W5500_IO_BASE_ 0x00000000 - -#define _W5500_SPI_READ_ (0x00 << 2) //< SPI interface Read operation in Control Phase -#define _W5500_SPI_WRITE_ (0x01 << 2) //< SPI interface Write operation in Control Phase - -#define WIZCHIP_CREG_BLOCK 0x00 //< Common register block -#define WIZCHIP_SREG_BLOCK(N) (1+4*N) //< Socket N register block -#define WIZCHIP_TXBUF_BLOCK(N) (2+4*N) //< Socket N Tx buffer address block -#define WIZCHIP_RXBUF_BLOCK(N) (3+4*N) //< Socket N Rx buffer address block - -#define WIZCHIP_OFFSET_INC(ADDR, N) (ADDR + (N<<8)) //< Increase offset address - - -/////////////////////////////////////// -// Definition For Legacy Chip Driver // -/////////////////////////////////////// -#define IINCHIP_READ(ADDR) WIZCHIP_READ(ADDR) ///< The defined for legacy chip driver -#define IINCHIP_WRITE(ADDR,VAL) WIZCHIP_WRITE(ADDR,VAL) ///< The defined for legacy chip driver -#define IINCHIP_READ_BUF(ADDR,BUF,LEN) WIZCHIP_READ_BUF(ADDR,BUF,LEN) ///< The defined for legacy chip driver -#define IINCHIP_WRITE_BUF(ADDR,BUF,LEN) WIZCHIP_WRITE(ADDR,BUF,LEN) ///< The defined for legacy chip driver - -////////////////////////////// -//-------------------------- defgroup --------------------------------- -/** - * @defgroup W5500 W5500 - * - * @brief WHIZCHIP register defines and I/O functions of @b W5500. - * - * - @ref WIZCHIP_register : @ref Common_register_group and @ref Socket_register_group - * - @ref WIZCHIP_IO_Functions : @ref Basic_IO_function, @ref Common_register_access_function and @ref Socket_register_access_function - */ - - -/** - * @defgroup WIZCHIP_register WIZCHIP register - * @ingroup W5500 - * - * @brief WHIZCHIP register defines register group of @b W5500. - * - * - @ref Common_register_group : Common register group - * - @ref Socket_register_group : \c SOCKET n register group - */ - - -/** - * @defgroup WIZCHIP_IO_Functions WIZCHIP I/O functions - * @ingroup W5500 - * - * @brief This supports the basic I/O functions for @ref WIZCHIP_register. - * - * - Basic I/O function \n - * WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() \n\n - * - * - @ref Common_register_group access functions \n - * -# @b Mode \n - * getMR(), setMR() - * -# @b Interrupt \n - * getIR(), setIR(), getIMR(), setIMR(), getSIR(), setSIR(), getSIMR(), setSIMR(), getINTLEVEL(), setINTLEVEL() - * -# Network Information \n - * getSHAR(), setSHAR(), getGAR(), setGAR(), getSUBR(), setSUBR(), getSIPR(), setSIPR() - * -# @b Retransmission \n - * getRCR(), setRCR(), getRTR(), setRTR() - * -# @b PPPoE \n - * getPTIMER(), setPTIMER(), getPMAGIC(), getPMAGIC(), getPSID(), setPSID(), getPHAR(), setPHAR(), getPMRU(), setPMRU() - * -# ICMP packet \n - * getUIPR(), getUPORTR() - * -# @b etc. \n - * getPHYCFGR(), setPHYCFGR(), getVERSIONR() \n\n - * - * - \ref Socket_register_group access functions \n - * -# SOCKET control \n - * getSn_MR(), setSn_MR(), getSn_CR(), setSn_CR(), getSn_IMR(), setSn_IMR(), getSn_IR(), setSn_IR() - * -# SOCKET information \n - * getSn_SR(), getSn_DHAR(), setSn_DHAR(), getSn_PORT(), setSn_PORT(), getSn_DIPR(), setSn_DIPR(), getSn_DPORT(), setSn_DPORT() - * getSn_MSSR(), setSn_MSSR() - * -# SOCKET communication \n - * getSn_RXBUF_SIZE(), setSn_RXBUF_SIZE(), getSn_TXBUF_SIZE(), setSn_TXBUF_SIZE() \n - * getSn_TX_RD(), getSn_TX_WR(), setSn_TX_WR() \n - * getSn_RX_RD(), setSn_RX_RD(), getSn_RX_WR() \n - * getSn_TX_FSR(), getSn_RX_RSR(), getSn_KPALVTR(), setSn_KPALVTR() - * -# IP header field \n - * getSn_FRAG(), setSn_FRAG(), getSn_TOS(), setSn_TOS() \n - * getSn_TTL(), setSn_TTL() - */ - - - -/** - * @defgroup Common_register_group Common register - * @ingroup WIZCHIP_register - * - * @brief Common register group\n - * It set the basic for the networking\n - * It set the configuration such as interrupt, network information, ICMP, etc. - * @details - * @sa MR : Mode register. - * @sa GAR, SUBR, SHAR, SIPR - * @sa INTLEVEL, IR, IMR, SIR, SIMR : Interrupt. - * @sa RTR, RCR : Data retransmission. - * @sa PTIMER, PMAGIC, PHAR, PSID, PMRU : PPPoE. - * @sa UIPR, UPORTR : ICMP message. - * @sa PHYCFGR, VERSIONR : etc. - */ - - - -/** - * @defgroup Socket_register_group Socket register - * @ingroup WIZCHIP_register - * - * @brief Socket register group.\n - * Socket register configures and control SOCKETn which is necessary to data communication. - * @details - * @sa Sn_MR, Sn_CR, Sn_IR, Sn_IMR : SOCKETn Control - * @sa Sn_SR, Sn_PORT, Sn_DHAR, Sn_DIPR, Sn_DPORT : SOCKETn Information - * @sa Sn_MSSR, Sn_TOS, Sn_TTL, Sn_KPALVTR, Sn_FRAG : Internet protocol. - * @sa Sn_RXBUF_SIZE, Sn_TXBUF_SIZE, Sn_TX_FSR, Sn_TX_RD, Sn_TX_WR, Sn_RX_RSR, Sn_RX_RD, Sn_RX_WR : Data communication - */ - - - - /** - * @defgroup Basic_IO_function Basic I/O function - * @ingroup WIZCHIP_IO_Functions - * @brief These are basic input/output functions to read values from register or write values to register. - */ - -/** - * @defgroup Common_register_access_function Common register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access common registers. - */ - -/** - * @defgroup Socket_register_access_function Socket register access functions - * @ingroup WIZCHIP_IO_Functions - * @brief These are functions to access socket registers. - */ - -//------------------------------- defgroup end -------------------------------------------- -//----------------------------- W5500 Common Registers IOMAP ----------------------------- -/** - * @ingroup Common_register_group - * @brief Mode Register address(R/W)\n - * @ref MR is used for S/W reset, ping block mode, PPPoE mode and etc. - * @details Each bit of @ref MR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
RST Reserved WOL PB PPPoE Reserved FARP Reserved
- * - \ref MR_RST : Reset - * - \ref MR_WOL : Wake on LAN - * - \ref MR_PB : Ping block - * - \ref MR_PPPOE : PPPoE mode - * - \ref MR_FARP : Force ARP mode - */ -#define MR (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Gateway IP Register address(R/W) - * @details @ref GAR configures the default gateway address. - */ -#define GAR (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Subnet mask Register address(R/W) - * @details @ref SUBR configures the subnet mask address. - */ -#define SUBR (_W5500_IO_BASE_ + (0x0005 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source MAC Register address(R/W) - * @details @ref SHAR configures the source hardware address. - */ -#define SHAR (_W5500_IO_BASE_ + (0x0009 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Source IP Register address(R/W) - * @details @ref SIPR configures the source IP address. - */ -#define SIPR (_W5500_IO_BASE_ + (0x000F << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Set Interrupt low level timer register address(R/W) - * @details @ref INTLEVEL configures the Interrupt Assert Time. - */ -#define INTLEVEL (_W5500_IO_BASE_ + (0x0013 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt Register(R/W) - * @details @ref IR indicates the interrupt status. Each bit of @ref IR will be still until the bit will be written to by the host. - * If @ref IR is not equal to x00 INTn PIN is asserted to low until it is x00\n\n - * Each bit of @ref IR defined as follows. - * - * - * - *
7 6 5 4 3 2 1 0
CONFLICT UNREACH PPPoE MP Reserved Reserved Reserved Reserved
- * - \ref IR_CONFLICT : IP conflict - * - \ref IR_UNREACH : Destination unreachable - * - \ref IR_PPPoE : PPPoE connection close - * - \ref IR_MP : Magic packet - */ -#define IR (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Interrupt mask register(R/W) - * @details @ref IMR is used to mask interrupts. Each bit of @ref IMR corresponds to each bit of @ref IR. - * When a bit of @ref IMR is and the corresponding bit of @ref IR is an interrupt will be issued. In other words, - * if a bit of @ref IMR is an interrupt will not be issued even if the corresponding bit of @ref IR is \n\n - * Each bit of @ref IMR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
IM_IR7 IM_IR6 IM_IR5 IM_IR4 Reserved Reserved Reserved Reserved
- * - \ref IM_IR7 : IP Conflict Interrupt Mask - * - \ref IM_IR6 : Destination unreachable Interrupt Mask - * - \ref IM_IR5 : PPPoE Close Interrupt Mask - * - \ref IM_IR4 : Magic Packet Interrupt Mask - */ -#define IMR (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Register(R/W) - * @details @ref SIR indicates the interrupt status of Socket.\n - * Each bit of @ref SIR be still until @ref Sn_IR is cleared by the host.\n - * If @ref Sn_IR is not equal to x00 the n-th bit of @ref SIR is and INTn PIN is asserted until @ref SIR is x00 */ -#define SIR (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Socket Interrupt Mask Register(R/W) - * @details Each bit of @ref SIMR corresponds to each bit of @ref SIR. - * When a bit of @ref SIMR is and the corresponding bit of @ref SIR is Interrupt will be issued. - * In other words, if a bit of @ref SIMR is an interrupt will be not issued even if the corresponding bit of @ref SIR is - */ -#define SIMR (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Timeout register address( 1 is 100us )(R/W) - * @details @ref RTR configures the retransmission timeout period. The unit of timeout period is 100us and the default of @ref RTR is x07D0or 000 - * And so the default timeout period is 200ms(100us X 2000). During the time configured by @ref RTR, W5500 waits for the peer response - * to the packet that is transmitted by \ref Sn_CR (CONNECT, DISCON, CLOSE, SEND, SEND_MAC, SEND_KEEP command). - * If the peer does not respond within the @ref RTR time, W5500 retransmits the packet or issues timeout. - */ -#define RTR (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Retry count register(R/W) - * @details @ref RCR configures the number of time of retransmission. - * When retransmission occurs as many as ref RCR+1 Timeout interrupt is issued (@ref Sn_IR[TIMEOUT] = . - */ -#define RCR (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Request Timer register in PPPoE mode(R/W) - * @details @ref PTIMER configures the time for sending LCP echo request. The unit of time is 25ms. - */ -#define PTIMER (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP LCP Magic number register in PPPoE mode(R/W) - * @details @ref PMAGIC configures the 4bytes magic number to be used in LCP negotiation. - */ -#define PMAGIC (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Destination MAC Register address(R/W) - * @details @ref PHAR configures the PPPoE server hardware address that is acquired during PPPoE connection process. - */ -#define PHAR (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Session Identification Register(R/W) - * @details @ref PSID configures the PPPoE sever session ID acquired during PPPoE connection process. - */ -#define PSID (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PPP Maximum Segment Size(MSS) register(R/W) - * @details @ref PMRU configures the maximum receive unit of PPPoE. - */ -#define PMRU (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable IP register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR indicates - * the destination IP address & port number respectively. - */ -#define UIPR (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief Unreachable Port register address in UDP mode(R) - * @details W5500 receives an ICMP packet(Destination port unreachable) when data is sent to a port number - * which socket is not open and @ref UNREACH bit of @ref IR becomes and @ref UIPR & @ref UPORTR - * indicates the destination IP address & port number respectively. - */ -#define UPORTR (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief PHY Status Register(R/W) - * @details @ref PHYCFGR configures PHY operation mode and resets PHY. In addition, @ref PHYCFGR indicates the status of PHY such as duplex, Speed, Link. - */ -#define PHYCFGR (_W5500_IO_BASE_ + (0x002E << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0031 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0032 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0033 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0034 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0035 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0036 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0037 << 8) + (WIZCHIP_CREG_BLOCK << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0038 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - -/** - * @ingroup Common_register_group - * @brief chip version register address(R) - * @details @ref VERSIONR always indicates the W5500 version as @b 0x04. - */ -#define VERSIONR (_W5500_IO_BASE_ + (0x0039 << 8) + (WIZCHIP_CREG_BLOCK << 3)) - - -//----------------------------- W5500 Socket Registers IOMAP ----------------------------- -/** - * @ingroup Socket_register_group - * @brief socket Mode register(R/W) - * @details @ref Sn_MR configures the option or protocol type of Socket n.\n\n - * Each bit of @ref Sn_MR defined as the following. - * - * - * - *
7 6 5 4 3 2 1 0
MULTI/MFEN BCASTB ND/MC/MMB UCASTB/MIP6B Protocol[3] Protocol[2] Protocol[1] Protocol[0]
- * - @ref Sn_MR_MULTI : Support UDP Multicasting - * - @ref Sn_MR_BCASTB : Broadcast block in UDP Multicasting - * - @ref Sn_MR_ND : No Delayed Ack(TCP) flag - * - @ref Sn_MR_MC : IGMP version used in UDP mulitcasting - * - @ref Sn_MR_MMB : Multicast Blocking in @ref Sn_MR_MACRAW mode - * - @ref Sn_MR_UCASTB : Unicast Block in UDP Multicating - * - @ref Sn_MR_MIP6B : IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * - Protocol - * - * - * - * - * - * - *
Protocol[3] Protocol[2] Protocol[1] Protocol[0] @b Meaning
0 0 0 0 Closed
0 0 0 1 TCP
0 0 1 0 UDP
0 1 0 0 MACRAW
- * - @ref Sn_MR_MACRAW : MAC LAYER RAW SOCK \n - * - @ref Sn_MR_UDP : UDP - * - @ref Sn_MR_TCP : TCP - * - @ref Sn_MR_CLOSE : Unused socket - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR(N) (_W5500_IO_BASE_ + (0x0000 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket command register(R/W) - * @details This is used to set the command for Socket n such as OPEN, CLOSE, CONNECT, LISTEN, SEND, and RECEIVE.\n - * After W5500 accepts the command, the @ref Sn_CR register is automatically cleared to 0x00. - * Even though @ref Sn_CR is cleared to 0x00, the command is still being processed.\n - * To check whether the command is completed or not, please check the @ref Sn_IR or @ref Sn_SR. - * - @ref Sn_CR_OPEN : Initialize or open socket. - * - @ref Sn_CR_LISTEN : Wait connection request in TCP mode(Server mode) - * - @ref Sn_CR_CONNECT : Send connection request in TCP mode(Client mode) - * - @ref Sn_CR_DISCON : Send closing request in TCP mode. - * - @ref Sn_CR_CLOSE : Close socket. - * - @ref Sn_CR_SEND : Update TX buffer pointer and send data. - * - @ref Sn_CR_SEND_MAC : Send data with MAC address, so without ARP process. - * - @ref Sn_CR_SEND_KEEP : Send keep alive message. - * - @ref Sn_CR_RECV : Update RX buffer pointer and receive data. - */ -#define Sn_CR(N) (_W5500_IO_BASE_ + (0x0001 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket interrupt register(R) - * @details @ref Sn_IR indicates the status of Socket Interrupt such as establishment, termination, receiving data, timeout).\n - * When an interrupt occurs and the corresponding bit of @ref Sn_IMR is the corresponding bit of @ref Sn_IR becomes \n - * In order to clear the @ref Sn_IR bit, the host should write the bit to \n - * - * - * - *
7 6 5 4 3 2 1 0
Reserved Reserved Reserved SEND_OK TIMEOUT RECV DISCON CON
- * - \ref Sn_IR_SENDOK : SEND_OK Interrupt - * - \ref Sn_IR_TIMEOUT : TIMEOUT Interrupt - * - \ref Sn_IR_RECV : RECV Interrupt - * - \ref Sn_IR_DISCON : DISCON Interrupt - * - \ref Sn_IR_CON : CON Interrupt - */ -#define Sn_IR(N) (_W5500_IO_BASE_ + (0x0002 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Socket status register(R) - * @details @ref Sn_SR indicates the status of Socket n.\n - * The status of Socket n is changed by @ref Sn_CR or some special control packet as SYN, FIN packet in TCP. - * @par Normal status - * - @ref SOCK_CLOSED : Closed - * - @ref SOCK_INIT : Initiate state - * - @ref SOCK_LISTEN : Listen state - * - @ref SOCK_ESTABLISHED : Success to connect - * - @ref SOCK_CLOSE_WAIT : Closing state - * - @ref SOCK_UDP : UDP socket - * - @ref SOCK_MACRAW : MAC raw mode socket - *@par Temporary status during changing the status of Socket n. - * - @ref SOCK_SYNSENT : This indicates Socket n sent the connect-request packet (SYN packet) to a peer. - * - @ref SOCK_SYNRECV : It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer. - * - @ref SOCK_FIN_WAIT : Connection state - * - @ref SOCK_CLOSING : Closing state - * - @ref SOCK_TIME_WAIT : Closing state - * - @ref SOCK_LAST_ACK : Closing state - */ -#define Sn_SR(N) (_W5500_IO_BASE_ + (0x0003 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief source port register(R/W) - * @details @ref Sn_PORT configures the source port number of Socket n. - * It is valid when Socket n is used in TCP/UPD mode. It should be set before OPEN command is ordered. - */ -#define Sn_PORT(N) (_W5500_IO_BASE_ + (0x0004 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer MAC register address(R/W) - * @details @ref Sn_DHAR configures the destination hardware address of Socket n when using SEND_MAC command in UDP mode or - * it indicates that it is acquired in ARP-process by CONNECT/SEND command. - */ -#define Sn_DHAR(N) (_W5500_IO_BASE_ + (0x0006 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer IP register address(R/W) - * @details @ref Sn_DIPR configures or indicates the destination IP address of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In TCP client mode, it configures an IP address of �TCP serverbefore CONNECT command. - * In TCP server mode, it indicates an IP address of �TCP clientafter successfully establishing connection. - * In UDP mode, it configures an IP address of peer to be received the UDP packet by SEND or SEND_MAC command. - */ -#define Sn_DIPR(N) (_W5500_IO_BASE_ + (0x000C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Peer port register address(R/W) - * @details @ref Sn_DPORT configures or indicates the destination port number of Socket n. It is valid when Socket n is used in TCP/UDP mode. - * In �TCP clientmode, it configures the listen port number of �TCP serverbefore CONNECT command. - * In �TCP Servermode, it indicates the port number of TCP client after successfully establishing connection. - * In UDP mode, it configures the port number of peer to be transmitted the UDP packet by SEND/SEND_MAC command. - */ -#define Sn_DPORT(N) (_W5500_IO_BASE_ + (0x0010 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Maximum Segment Size(Sn_MSSR0) register address(R/W) - * @details @ref Sn_MSSR configures or indicates the MTU(Maximum Transfer Unit) of Socket n. - */ -#define Sn_MSSR(N) (_W5500_IO_BASE_ + (0x0012 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -// Reserved (_W5500_IO_BASE_ + (0x0014 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief IP Type of Service(TOS) Register(R/W) - * @details @ref Sn_TOS configures the TOS(Type Of Service field in IP Header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TOS(N) (_W5500_IO_BASE_ + (0x0015 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -/** - * @ingroup Socket_register_group - * @brief IP Time to live(TTL) Register(R/W) - * @details @ref Sn_TTL configures the TTL(Time To Live field in IP header) of Socket n. - * It is set before OPEN command. - */ -#define Sn_TTL(N) (_W5500_IO_BASE_ + (0x0016 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0017 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0018 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x0019 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001B << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) -// Reserved (_W5500_IO_BASE_ + (0x001D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Receive memory size register(R/W) - * @details @ref Sn_RXBUF_SIZE configures the RX buffer block size of Socket n. - * Socket n RX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data cannot be normally received from a peer. - * Although Socket n RX Buffer Block size is initially configured to 2Kbytes, - * user can re-configure its size using @ref Sn_RXBUF_SIZE. The total sum of @ref Sn_RXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data reception error is occurred. - */ -#define Sn_RXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001E << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory size register(R/W) - * @details @ref Sn_TXBUF_SIZE configures the TX buffer block size of Socket n. Socket n TX Buffer Block size can be configured with 1,2,4,8, and 16 Kbytes. - * If a different size is configured, the data can�t be normally transmitted to a peer. - * Although Socket n TX Buffer Block size is initially configured to 2Kbytes, - * user can be re-configure its size using @ref Sn_TXBUF_SIZE. The total sum of @ref Sn_TXBUF_SIZE can not be exceed 16Kbytes. - * When exceeded, the data transmission error is occurred. - */ -#define Sn_TXBUF_SIZE(N) (_W5500_IO_BASE_ + (0x001F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit free memory size register(R) - * @details @ref Sn_TX_FSR indicates the free size of Socket n TX Buffer Block. It is initialized to the configured size by @ref Sn_TXBUF_SIZE. - * Data bigger than @ref Sn_TX_FSR should not be saved in the Socket n TX Buffer because the bigger data overwrites the previous saved data not yet sent. - * Therefore, check before saving the data to the Socket n TX Buffer, and if data is equal or smaller than its checked size, - * transmit the data with SEND/SEND_MAC command after saving the data in Socket n TX buffer. But, if data is bigger than its checked size, - * transmit the data after dividing into the checked size and saving in the Socket n TX buffer. - */ -#define Sn_TX_FSR(N) (_W5500_IO_BASE_ + (0x0020 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory read pointer register address(R) - * @details @ref Sn_TX_RD is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP. - * After its initialization, it is auto-increased by SEND command. - * SEND command transmits the saved data from the current @ref Sn_TX_RD to the @ref Sn_TX_WR in the Socket n TX Buffer. - * After transmitting the saved data, the SEND command increases the @ref Sn_TX_RD as same as the @ref Sn_TX_WR. - * If its increment value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_TX_RD(N) (_W5500_IO_BASE_ + (0x0022 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Transmit memory write pointer register address(R/W) - * @details @ref Sn_TX_WR is initialized by OPEN command. However, if Sn_MR(P[3:0]) is TCP mode(001, it is re-initialized while connecting with TCP.\n - * It should be read or be updated like as follows.\n - * 1. Read the starting address for saving the transmitting data.\n - * 2. Save the transmitting data from the starting address of Socket n TX buffer.\n - * 3. After saving the transmitting data, update @ref Sn_TX_WR to the increased value as many as transmitting data size. - * If the increment value exceeds the maximum value 0xFFFF(greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value.\n - * 4. Transmit the saved data in Socket n TX Buffer by using SEND/SEND command - */ -#define Sn_TX_WR(N) (_W5500_IO_BASE_ + (0x0024 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Received data size register(R) - * @details @ref Sn_RX_RSR indicates the data size received and saved in Socket n RX Buffer. - * @ref Sn_RX_RSR does not exceed the @ref Sn_RXBUF_SIZE and is calculated as the difference between - * �Socket n RX Write Pointer (@ref Sn_RX_WR)and �Socket n RX Read Pointer (@ref Sn_RX_RD) - */ -#define Sn_RX_RSR(N) (_W5500_IO_BASE_ + (0x0026 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Read point of Receive memory(R/W) - * @details @ref Sn_RX_RD is initialized by OPEN command. Make sure to be read or updated as follows.\n - * 1. Read the starting save address of the received data.\n - * 2. Read data from the starting address of Socket n RX Buffer.\n - * 3. After reading the received data, Update @ref Sn_RX_RD to the increased value as many as the reading size. - * If the increment value exceeds the maximum value 0xFFFF, that is, is greater than 0x10000 and the carry bit occurs, - * update with the lower 16bits value ignored the carry bit.\n - * 4. Order RECV command is for notifying the updated @ref Sn_RX_RD to W5500. - */ -#define Sn_RX_RD(N) (_W5500_IO_BASE_ + (0x0028 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Write point of Receive memory(R) - * @details @ref Sn_RX_WR is initialized by OPEN command and it is auto-increased by the data reception. - * If the increased value exceeds the maximum value 0xFFFF, (greater than 0x10000 and the carry bit occurs), - * then the carry bit is ignored and will automatically update with the lower 16bits value. - */ -#define Sn_RX_WR(N) (_W5500_IO_BASE_ + (0x002A << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief socket interrupt mask register(R) - * @details @ref Sn_IMR masks the interrupt of Socket n. - * Each bit corresponds to each bit of @ref Sn_IR. When a Socket n Interrupt is occurred and the corresponding bit of @ref Sn_IMR is - * the corresponding bit of @ref Sn_IR becomes When both the corresponding bit of @ref Sn_IMR and @ref Sn_IR are and the n-th bit of @ref IR is - * Host is interrupted by asserted INTn PIN to low. - */ -#define Sn_IMR(N) (_W5500_IO_BASE_ + (0x002C << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Fragment field value in IP header register(R/W) - * @details @ref Sn_FRAG configures the FRAG(Fragment field in IP header). - */ -#define Sn_FRAG(N) (_W5500_IO_BASE_ + (0x002D << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -/** - * @ingroup Socket_register_group - * @brief Keep Alive Timer register(R/W) - * @details @ref Sn_KPALVTR configures the transmitting timer of �KEEP ALIVE(KA)packet of SOCKETn. It is valid only in TCP mode, - * and ignored in other modes. The time unit is 5s. - * KA packet is transmittable after @ref Sn_SR is changed to SOCK_ESTABLISHED and after the data is transmitted or received to/from a peer at least once. - * In case of '@ref Sn_KPALVTR > 0', W5500 automatically transmits KA packet after time-period for checking the TCP connection (Auto-keepalive-process). - * In case of '@ref Sn_KPALVTR = 0', Auto-keep-alive-process will not operate, - * and KA packet can be transmitted by SEND_KEEP command by the host (Manual-keep-alive-process). - * Manual-keep-alive-process is ignored in case of '@ref Sn_KPALVTR > 0'. - */ -#define Sn_KPALVTR(N) (_W5500_IO_BASE_ + (0x002F << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - -//#define Sn_TSR(N) (_W5500_IO_BASE_ + (0x0030 << 8) + (WIZCHIP_SREG_BLOCK(N) << 3)) - - -//----------------------------- W5500 Register values ----------------------------- - -/* MODE register values */ -/** - * @brief Reset - * @details If this bit is All internal registers will be initialized. It will be automatically cleared as after S/W reset. - */ -#define MR_RST 0x80 - -/** - * @brief Wake on LAN - * @details 0 : Disable WOL mode\n - * 1 : Enable WOL mode\n - * If WOL mode is enabled and the received magic packet over UDP has been normally processed, the Interrupt PIN (INTn) asserts to low. - * When using WOL mode, the UDP Socket should be opened with any source port number. (Refer to Socket n Mode Register (@ref Sn_MR) for opening Socket.) - * @note The magic packet over UDP supported by W5500 consists of 6 bytes synchronization stream (xFFFFFFFFFFFF and - * 16 times Target MAC address stream in UDP payload. The options such like password are ignored. You can use any UDP source port number for WOL mode. - */ -#define MR_WOL 0x20 - -/** - * @brief Ping block - * @details 0 : Disable Ping block\n - * 1 : Enable Ping block\n - * If the bit is it blocks the response to a ping request. - */ -#define MR_PB 0x10 - -/** - * @brief Enable PPPoE - * @details 0 : DisablePPPoE mode\n - * 1 : EnablePPPoE mode\n - * If you use ADSL, this bit should be - */ -#define MR_PPPOE 0x08 - -/** - * @brief Enable UDP_FORCE_ARP CHECHK - * @details 0 : Disable Force ARP mode\n - * 1 : Enable Force ARP mode\n - * In Force ARP mode, It forces on sending ARP Request whenever data is sent. - */ -#define MR_FARP 0x02 - -/* IR register values */ -/** - * @brief Check IP conflict. - * @details Bit is set as when own source IP address is same with the sender IP address in the received ARP request. - */ -#define IR_CONFLICT 0x80 - -/** - * @brief Get the destination unreachable message in UDP sending. - * @details When receiving the ICMP (Destination port unreachable) packet, this bit is set as - * When this bit is Destination Information such as IP address and Port number may be checked with the corresponding @ref UIPR & @ref UPORTR. - */ -#define IR_UNREACH 0x40 - -/** - * @brief Get the PPPoE close message. - * @details When PPPoE is disconnected during PPPoE mode, this bit is set. - */ -#define IR_PPPoE 0x20 - -/** - * @brief Get the magic packet interrupt. - * @details When WOL mode is enabled and receives the magic packet over UDP, this bit is set. - */ -#define IR_MP 0x10 - - -/* PHYCFGR register value */ -#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. -#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value -#define PHYCFGR_OPMDC_ALLA (7<<3) -#define PHYCFGR_OPMDC_PDOWN (6<<3) -#define PHYCFGR_OPMDC_NA (5<<3) -#define PHYCFGR_OPMDC_100FA (4<<3) -#define PHYCFGR_OPMDC_100F (3<<3) -#define PHYCFGR_OPMDC_100H (2<<3) -#define PHYCFGR_OPMDC_10F (1<<3) -#define PHYCFGR_OPMDC_10H (0<<3) -#define PHYCFGR_DPX_FULL (1<<2) -#define PHYCFGR_DPX_HALF (0<<2) -#define PHYCFGR_SPD_100 (1<<1) -#define PHYCFGR_SPD_10 (0<<1) -#define PHYCFGR_LNK_ON (1<<0) -#define PHYCFGR_LNK_OFF (0<<0) - -/* IMR register values */ -/** - * @brief IP Conflict Interrupt Mask. - * @details 0: Disable IP Conflict Interrupt\n - * 1: Enable IP Conflict Interrupt - */ -#define IM_IR7 0x80 - -/** - * @brief Destination unreachable Interrupt Mask. - * @details 0: Disable Destination unreachable Interrupt\n - * 1: Enable Destination unreachable Interrupt - */ -#define IM_IR6 0x40 - -/** - * @brief PPPoE Close Interrupt Mask. - * @details 0: Disable PPPoE Close Interrupt\n - * 1: Enable PPPoE Close Interrupt - */ -#define IM_IR5 0x20 - -/** - * @brief Magic Packet Interrupt Mask. - * @details 0: Disable Magic Packet Interrupt\n - * 1: Enable Magic Packet Interrupt - */ -#define IM_IR4 0x10 - -/* Sn_MR Default values */ -/** - * @brief Support UDP Multicasting - * @details 0 : disable Multicasting\n - * 1 : enable Multicasting\n - * This bit is applied only during UDP mode(P[3:0] = 010.\n - * To use multicasting, @ref Sn_DIPR & @ref Sn_DPORT should be respectively configured with the multicast group IP address & port number - * before Socket n is opened by OPEN command of @ref Sn_CR. - */ -#define Sn_MR_MULTI 0x80 - -/** - * @brief Broadcast block in UDP Multicasting. - * @details 0 : disable Broadcast Blocking\n - * 1 : enable Broadcast Blocking\n - * This bit blocks to receive broadcasting packet during UDP mode(P[3:0] = 010.\m - * In addition, This bit does when MACRAW mode(P[3:0] = 100 - */ -#define Sn_MR_BCASTB 0x40 - -/** - * @brief No Delayed Ack(TCP), Multicast flag - * @details 0 : Disable No Delayed ACK option\n - * 1 : Enable No Delayed ACK option\n - * This bit is applied only during TCP mode (P[3:0] = 001.\n - * When this bit is It sends the ACK packet without delay as soon as a Data packet is received from a peer.\n - * When this bit is It sends the ACK packet after waiting for the timeout time configured by @ref RTR. - */ -#define Sn_MR_ND 0x20 - -/** - * @brief Unicast Block in UDP Multicasting - * @details 0 : disable Unicast Blocking\n - * 1 : enable Unicast Blocking\n - * This bit blocks receiving the unicast packet during UDP mode(P[3:0] = 010 and MULTI = - */ -#define Sn_MR_UCASTB 0x10 - -/** - * @brief MAC LAYER RAW SOCK - * @details This configures the protocol mode of Socket n. - * @note MACRAW mode should be only used in Socket 0. - */ -#define Sn_MR_MACRAW 0x04 - -//#define Sn_MR_IPRAW 0x03 /**< IP LAYER RAW SOCK */ - -/** - * @brief UDP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_UDP 0x02 - -/** - * @brief TCP - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_TCP 0x01 - -/** - * @brief Unused socket - * @details This configures the protocol mode of Socket n. - */ -#define Sn_MR_CLOSE 0x00 - -/* Sn_MR values used with Sn_MR_MACRAW */ -/** - * @brief MAC filter enable in @ref Sn_MR_MACRAW mode - * @details 0 : disable MAC Filtering\n - * 1 : enable MAC Filtering\n - * This bit is applied only during MACRAW mode(P[3:0] = 100.\n - * When set as W5500 can only receive broadcasting packet or packet sent to itself. - * When this bit is W5500 can receive all packets on Ethernet. - * If user wants to implement Hybrid TCP/IP stack, - * it is recommended that this bit is set as for reducing host overhead to process the all received packets. - */ -#define Sn_MR_MFEN Sn_MR_MULTI - -/** - * @brief Multicast Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : using IGMP version 2\n - * 1 : using IGMP version 1\n - * This bit is applied only during UDP mode(P[3:0] = 010 and MULTI = - * It configures the version for IGMP messages (Join/Leave/Report). - */ -#define Sn_MR_MMB Sn_MR_ND - -/** - * @brief IPv6 packet Blocking in @ref Sn_MR_MACRAW mode - * @details 0 : disable IPv6 Blocking\n - * 1 : enable IPv6 Blocking\n - * This bit is applied only during MACRAW mode (P[3:0] = 100. It blocks to receiving the IPv6 packet. - */ -#define Sn_MR_MIP6B Sn_MR_UCASTB - -/* Sn_MR value used with Sn_MR_UDP & Sn_MR_MULTI */ -/** - * @brief IGMP version used in UDP mulitcasting - * @details 0 : disable Multicast Blocking\n - * 1 : enable Multicast Blocking\n - * This bit is applied only when MACRAW mode(P[3:0] = 100. It blocks to receive the packet with multicast MAC address. - */ -#define Sn_MR_MC Sn_MR_ND - -/* Sn_MR alternate values */ -/** - * @brief For Berkeley Socket API - */ -#define SOCK_STREAM Sn_MR_TCP - -/** - * @brief For Berkeley Socket API - */ -#define SOCK_DGRAM Sn_MR_UDP - - -/* Sn_CR values */ -/** - * @brief Initialize or open socket - * @details Socket n is initialized and opened according to the protocol selected in Sn_MR(P3:P0). - * The table below shows the value of @ref Sn_SR corresponding to @ref Sn_MR.\n - * - * - * - * - * - * - *
\b Sn_MR (P[3:0]) \b Sn_SR
Sn_MR_CLOSE (000
Sn_MR_TCP (001 SOCK_INIT (0x13)
Sn_MR_UDP (010 SOCK_UDP (0x22)
S0_MR_MACRAW (100 SOCK_MACRAW (0x02)
- */ -#define Sn_CR_OPEN 0x01 - -/** - * @brief Wait connection request in TCP mode(Server mode) - * @details This is valid only in TCP mode (Sn_MR(P3:P0) = Sn_MR_TCP). - * In this mode, Socket n operates as a �TCP serverand waits for connection-request (SYN packet) from any �TCP client - * The @ref Sn_SR changes the state from SOCK_INIT to SOCKET_LISTEN. - * When a �TCP clientconnection request is successfully established, - * the @ref Sn_SR changes from SOCK_LISTEN to SOCK_ESTABLISHED and the Sn_IR(0) becomes - * But when a �TCP clientconnection request is failed, Sn_IR(3) becomes and the status of @ref Sn_SR changes to SOCK_CLOSED. - */ -#define Sn_CR_LISTEN 0x02 - -/** - * @brief Send connection request in TCP mode(Client mode) - * @details To connect, a connect-request (SYN packet) is sent to b>TCP serverconfigured by @ref Sn_DIPR & Sn_DPORT(destination address & port). - * If the connect-request is successful, the @ref Sn_SR is changed to @ref SOCK_ESTABLISHED and the Sn_IR(0) becomes \n\n - * The connect-request fails in the following three cases.\n - * 1. When a @b ARPTO occurs (@ref Sn_IR[3] = ) because destination hardware address is not acquired through the ARP-process.\n - * 2. When a @b SYN/ACK packet is not received and @b TCPTO (Sn_IR(3) = )\n - * 3. When a @b RST packet is received instead of a @b SYN/ACK packet. In these cases, @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note This is valid only in TCP mode and operates when Socket n acts as b>TCP client - */ -#define Sn_CR_CONNECT 0x04 - -/** - * @brief Send closing request in TCP mode - * @details Regardless of b>TCP serveror b>TCP client the DISCON command processes the disconnect-process (b>Active closeor b>Passive close.\n - * @par Active close - * it transmits disconnect-request(FIN packet) to the connected peer\n - * @par Passive close - * When FIN packet is received from peer, a FIN packet is replied back to the peer.\n - * @details When the disconnect-process is successful (that is, FIN/ACK packet is received successfully), @ref Sn_SR is changed to @ref SOCK_CLOSED.\n - * Otherwise, TCPTO occurs (Sn_IR(3)=)= and then @ref Sn_SR is changed to @ref SOCK_CLOSED. - * @note Valid only in TCP mode. - */ -#define Sn_CR_DISCON 0x08 - -/** - * @brief Close socket - * @details Sn_SR is changed to @ref SOCK_CLOSED. - */ -#define Sn_CR_CLOSE 0x10 - -/** - * @brief Update TX buffer pointer and send data - * @details SEND transmits all the data in the Socket n TX buffer.\n - * For more details, please refer to Socket n TX Free Size Register (@ref Sn_TX_FSR), Socket n, - * TX Write Pointer Register(@ref Sn_TX_WR), and Socket n TX Read Pointer Register(@ref Sn_TX_RD). - */ -#define Sn_CR_SEND 0x20 - -/** - * @brief Send data with MAC address, so without ARP process - * @details The basic operation is same as SEND.\n - * Normally SEND transmits data after destination hardware address is acquired by the automatic ARP-process(Address Resolution Protocol).\n - * But SEND_MAC transmits data without the automatic ARP-process.\n - * In this case, the destination hardware address is acquired from @ref Sn_DHAR configured by host, instead of APR-process. - * @note Valid only in UDP mode. - */ -#define Sn_CR_SEND_MAC 0x21 - -/** - * @brief Send keep alive message - * @details It checks the connection status by sending 1byte keep-alive packet.\n - * If the peer can not respond to the keep-alive packet during timeout time, the connection is terminated and the timeout interrupt will occur. - * @note Valid only in TCP mode. - */ -#define Sn_CR_SEND_KEEP 0x22 - -/** - * @brief Update RX buffer pointer and receive data - * @details RECV completes the processing of the received data in Socket n RX Buffer by using a RX read pointer register (@ref Sn_RX_RD).\n - * For more details, refer to Socket n RX Received Size Register (@ref Sn_RX_RSR), Socket n RX Write Pointer Register (@ref Sn_RX_WR), - * and Socket n RX Read Pointer Register (@ref Sn_RX_RD). - */ -#define Sn_CR_RECV 0x40 - -/* Sn_IR values */ -/** - * @brief SEND_OK Interrupt - * @details This is issued when SEND command is completed. - */ -#define Sn_IR_SENDOK 0x10 - -/** - * @brief TIMEOUT Interrupt - * @details This is issued when ARPTO or TCPTO occurs. - */ -#define Sn_IR_TIMEOUT 0x08 - -/** - * @brief RECV Interrupt - * @details This is issued whenever data is received from a peer. - */ -#define Sn_IR_RECV 0x04 - -/** - * @brief DISCON Interrupt - * @details This is issued when FIN or FIN/ACK packet is received from a peer. - */ -#define Sn_IR_DISCON 0x02 - -/** - * @brief CON Interrupt - * @details This is issued one time when the connection with peer is successful and then @ref Sn_SR is changed to @ref SOCK_ESTABLISHED. - */ -#define Sn_IR_CON 0x01 - -/* Sn_SR values */ -/** - * @brief Closed - * @details This indicates that Socket n is released.\N - * When DICON, CLOSE command is ordered, or when a timeout occurs, it is changed to @ref SOCK_CLOSED regardless of previous status. - */ -#define SOCK_CLOSED 0x00 - -/** - * @brief Initiate state - * @details This indicates Socket n is opened with TCP mode.\N - * It is changed to @ref SOCK_INIT when Sn_MR(P[3:0]) = 001and OPEN command is ordered.\N - * After @ref SOCK_INIT, user can use LISTEN /CONNECT command. - */ -#define SOCK_INIT 0x13 - -/** - * @brief Listen state - * @details This indicates Socket n is operating as b>TCP servermode and waiting for connection-request (SYN packet) from a peer (b>TCP client.\n - * It will change to @ref SOCK_ESTALBLISHED when the connection-request is successfully accepted.\n - * Otherwise it will change to @ref SOCK_CLOSED after TCPTO occurred (Sn_IR(TIMEOUT) = . - */ -#define SOCK_LISTEN 0x14 - -/** - * @brief Connection state - * @details This indicates Socket n sent the connect-request packet (SYN packet) to a peer.\n - * It is temporarily shown when @ref Sn_SR is changed from @ref SOCK_INIT to @ref SOCK_ESTABLISHED by CONNECT command.\n - * If connect-accept(SYN/ACK packet) is received from the peer at SOCK_SYNSENT, it changes to @ref SOCK_ESTABLISHED.\n - * Otherwise, it changes to @ref SOCK_CLOSED after TCPTO (@ref Sn_IR[TIMEOUT] = is occurred. - */ -#define SOCK_SYNSENT 0x15 - -/** - * @brief Connection state - * @details It indicates Socket n successfully received the connect-request packet (SYN packet) from a peer.\n - * If socket n sends the response (SYN/ACK packet) to the peer successfully, it changes to @ref SOCK_ESTABLISHED. \n - * If not, it changes to @ref SOCK_CLOSED after timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_SYNRECV 0x16 - -/** - * @brief Success to connect - * @details This indicates the status of the connection of Socket n.\n - * It changes to @ref SOCK_ESTABLISHED when the b>TCP SERVERprocessed the SYN packet from the b>TCP CLIENTduring @ref SOCK_LISTEN, or - * when the CONNECT command is successful.\n - * During @ref SOCK_ESTABLISHED, DATA packet can be transferred using SEND or RECV command. - */ -#define SOCK_ESTABLISHED 0x17 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_FIN_WAIT 0x18 - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_CLOSING 0x1A - -/** - * @brief Closing state - * @details These indicate Socket n is closing.\n - * These are shown in disconnect-process such as active-close and passive-close.\n - * When Disconnect-process is successfully completed, or when timeout occurs, these change to @ref SOCK_CLOSED. - */ -#define SOCK_TIME_WAIT 0x1B - -/** - * @brief Closing state - * @details This indicates Socket n received the disconnect-request (FIN packet) from the connected peer.\n - * This is half-closing status, and data can be transferred.\n - * For full-closing, DISCON command is used. But For just-closing, CLOSE command is used. - */ -#define SOCK_CLOSE_WAIT 0x1C - -/** - * @brief Closing state - * @details This indicates Socket n is waiting for the response (FIN/ACK packet) to the disconnect-request (FIN packet) by passive-close.\n - * It changes to @ref SOCK_CLOSED when Socket n received the response successfully, or when timeout occurs (@ref Sn_IR[TIMEOUT] = . - */ -#define SOCK_LAST_ACK 0x1D - -/** - * @brief UDP socket - * @details This indicates Socket n is opened in UDP mode(Sn_MR(P[3:0]) = 010.\n - * It changes to SOCK_UPD when Sn_MR(P[3:0]) = 010 and OPEN command is ordered.\n - * Unlike TCP mode, data can be transfered without the connection-process. - */ -#define SOCK_UDP 0x22 - -//#define SOCK_IPRAW 0x32 /**< IP raw mode socket */ - -/** - * @brief MAC raw mode socket - * @details This indicates Socket 0 is opened in MACRAW mode (S0_MR(P[3:0]) = 100and is valid only in Socket 0.\n - * It changes to SOCK_MACRAW when S0_MR(P[3:0] = 100and OPEN command is ordered.\n - * Like UDP mode socket, MACRAW mode Socket 0 can transfer a MAC packet (Ethernet frame) without the connection-process. - */ -#define SOCK_MACRAW 0x42 - -//#define SOCK_PPPOE 0x5F - -/* IP PROTOCOL */ -#define IPPROTO_IP 0 //< Dummy for IP -#define IPPROTO_ICMP 1 //< Control message protocol -#define IPPROTO_IGMP 2 //< Internet group management protocol -#define IPPROTO_GGP 3 //< Gateway^2 (deprecated) -#define IPPROTO_TCP 6 //< TCP -#define IPPROTO_PUP 12 //< PUP -#define IPPROTO_UDP 17 //< UDP -#define IPPROTO_IDP 22 //< XNS idp -#define IPPROTO_ND 77 //< UNOFFICIAL net disk protocol -#define IPPROTO_RAW 255 //< Raw IP packet - - -/** - * @brief Enter a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n \n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt.\n - * In OS environment, You can replace it to critical section api supported by OS. - * - * \sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * \sa WIZCHIP_CRITICAL_EXIT() - */ -#define WIZCHIP_CRITICAL_ENTER() WIZCHIP.CRIS._enter() - -/** - * @brief Exit a critical section - * - * @details It is provided to protect your shared code which are executed without distribution. \n\n - * - * In non-OS environment, It can be just implemented by disabling whole interrupt. \n - * In OS environment, You can replace it to critical section api supported by OS. - * - * @sa WIZCHIP_READ(), WIZCHIP_WRITE(), WIZCHIP_READ_BUF(), WIZCHIP_WRITE_BUF() - * @sa WIZCHIP_CRITICAL_ENTER() - */ -#ifdef _exit -#undef _exit -#endif -#define WIZCHIP_CRITICAL_EXIT() WIZCHIP.CRIS._exit() - - - -//////////////////////// -// Basic I/O Function // -//////////////////////// - -/** - * @ingroup Basic_IO_function - * @brief It reads 1 byte value from a register. - * @param AddrSel Register address - * @return The value of register - */ -uint8_t WIZCHIP_READ (uint32_t AddrSel); - -/** - * @ingroup Basic_IO_function - * @brief It writes 1 byte value to a register. - * @param AddrSel Register address - * @param wb Write data - * @return void - */ -void WIZCHIP_WRITE(uint32_t AddrSel, uint8_t wb ); - -/** - * @ingroup Basic_IO_function - * @brief It reads sequence data from registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to read data - * @param len Data length - */ -void WIZCHIP_READ_BUF (uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It writes sequence data to registers. - * @param AddrSel Register address - * @param pBuf Pointer buffer to write data - * @param len Data length - */ -void WIZCHIP_WRITE_BUF(uint32_t AddrSel, uint8_t* pBuf, uint16_t len); - -///////////////////////////////// -// Common Register I/O function // -///////////////////////////////// -/** - * @ingroup Common_register_access_function - * @brief Set Mode Register - * @param (uint8_t)mr The value to be set. - * @sa getMR() - */ -#define setMR(mr) \ - WIZCHIP_WRITE(MR,mr) - - -/** - * @ingroup Common_register_access_function - * @brief Get Mode Register - * @return uint8_t. The value of Mode register. - * @sa setMR() - */ -#define getMR() \ - WIZCHIP_READ(MR) - -/** - * @ingroup Common_register_access_function - * @brief Set gateway IP address - * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. - * @sa getGAR() - */ -#define setGAR(gar) \ - WIZCHIP_WRITE_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Get gateway IP address - * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. - * @sa setGAR() - */ -#define getGAR(gar) \ - WIZCHIP_READ_BUF(GAR,gar,4) - -/** - * @ingroup Common_register_access_function - * @brief Set subnet mask address - * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. - * @sa getSUBR() - */ -#define setSUBR(subr) \ - WIZCHIP_WRITE_BUF(SUBR, subr,4) - - -/** - * @ingroup Common_register_access_function - * @brief Get subnet mask address - * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. - * @sa setSUBR() - */ -#define getSUBR(subr) \ - WIZCHIP_READ_BUF(SUBR, subr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set local MAC address - * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. - * @sa getSHAR() - */ -#define setSHAR(shar) \ - WIZCHIP_WRITE_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local MAC address - * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. - * @sa setSHAR() - */ -#define getSHAR(shar) \ - WIZCHIP_READ_BUF(SHAR, shar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set local IP address - * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. - * @sa getSIPR() - */ -#define setSIPR(sipr) \ - WIZCHIP_WRITE_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. - * @sa setSIPR() - */ -#define getSIPR(sipr) \ - WIZCHIP_READ_BUF(SIPR, sipr, 4) - -/** - * @ingroup Common_register_access_function - * @brief Set INTLEVEL register - * @param (uint16_t)intlevel Value to set @ref INTLEVEL register. - * @sa getINTLEVEL() - */ -#define setINTLEVEL(intlevel) {\ - WIZCHIP_WRITE(INTLEVEL, (uint8_t)(intlevel >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(INTLEVEL,1), (uint8_t) intlevel); \ - } - - -/** - * @ingroup Common_register_access_function - * @brief Get INTLEVEL register - * @return uint16_t. Value of @ref INTLEVEL register. - * @sa setINTLEVEL() - */ -#define getINTLEVEL() \ - ((WIZCHIP_READ(INTLEVEL) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(INTLEVEL,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref IR register - * @param (uint8_t)ir Value to set @ref IR register. - * @sa getIR() - */ -#define setIR(ir) \ - WIZCHIP_WRITE(IR, (ir & 0xF0)) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IR register - * @return uint8_t. Value of @ref IR register. - * @sa setIR() - */ -#define getIR() \ - (WIZCHIP_READ(IR) & 0xF0) -/** - * @ingroup Common_register_access_function - * @brief Set @ref IMR register - * @param (uint8_t)imr Value to set @ref IMR register. - * @sa getIMR() - */ -#define setIMR(imr) \ - WIZCHIP_WRITE(IMR, imr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref IMR register - * @return uint8_t. Value of @ref IMR register. - * @sa setIMR() - */ -#define getIMR() \ - WIZCHIP_READ(IMR) - - -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIR register - * @param (uint8_t)sir Value to set @ref SIR register. - * @sa getSIR() - */ -#define setSIR(sir) \ - WIZCHIP_WRITE(SIR, sir) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIR register - * @return uint8_t. Value of @ref SIR register. - * @sa setSIR() - */ -#define getSIR() \ - WIZCHIP_READ(SIR) -/** - * @ingroup Common_register_access_function - * @brief Set @ref SIMR register - * @param (uint8_t)simr Value to set @ref SIMR register. - * @sa getSIMR() - */ -#define setSIMR(simr) \ - WIZCHIP_WRITE(SIMR, simr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref SIMR register - * @return uint8_t. Value of @ref SIMR register. - * @sa setSIMR() - */ -#define getSIMR() \ - WIZCHIP_READ(SIMR) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RTR register - * @param (uint16_t)rtr Value to set @ref RTR register. - * @sa getRTR() - */ -#define setRTR(rtr) {\ - WIZCHIP_WRITE(RTR, (uint8_t)(rtr >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(RTR,1), (uint8_t) rtr); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RTR register - * @return uint16_t. Value of @ref RTR register. - * @sa setRTR() - */ -#define getRTR() \ - ((WIZCHIP_READ(RTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(RTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref RCR register - * @param (uint8_t)rcr Value to set @ref RCR register. - * @sa getRCR() - */ -#define setRCR(rcr) \ - WIZCHIP_WRITE(RCR, rcr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref RCR register - * @return uint8_t. Value of @ref RCR register. - * @sa setRCR() - */ -#define getRCR() \ - WIZCHIP_READ(RCR) - -//================================================== test done =========================================================== - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PTIMER register - * @param (uint8_t)ptimer Value to set @ref PTIMER register. - * @sa getPTIMER() - */ -#define setPTIMER(ptimer) \ - WIZCHIP_WRITE(PTIMER, ptimer) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PTIMER register - * @return uint8_t. Value of @ref PTIMER register. - * @sa setPTIMER() - */ -#define getPTIMER() \ - WIZCHIP_READ(PTIMER) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMAGIC register - * @param (uint8_t)pmagic Value to set @ref PMAGIC register. - * @sa getPMAGIC() - */ -#define setPMAGIC(pmagic) \ - WIZCHIP_WRITE(PMAGIC, pmagic) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMAGIC register - * @return uint8_t. Value of @ref PMAGIC register. - * @sa setPMAGIC() - */ -#define getPMAGIC() \ - WIZCHIP_READ(PMAGIC) - -/** - * @ingroup Common_register_access_function - * @brief Set PHAR address - * @param (uint8_t*)phar Pointer variable to set PPP destination MAC register address. It should be allocated 6 bytes. - * @sa getPHAR() - */ -#define setPHAR(phar) \ - WIZCHIP_WRITE_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Get local IP address - * @param (uint8_t*)phar Pointer variable to PPP destination MAC register address. It should be allocated 6 bytes. - * @sa setPHAR() - */ -#define getPHAR(phar) \ - WIZCHIP_READ_BUF(PHAR, phar, 6) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PSID register - * @param (uint16_t)psid Value to set @ref PSID register. - * @sa getPSID() - */ -#define setPSID(psid) {\ - WIZCHIP_WRITE(PSID, (uint8_t)(psid >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PSID,1), (uint8_t) psid); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PSID register - * @return uint16_t. Value of @ref PSID register. - * @sa setPSID() - */ -//uint16_t getPSID(void); -#define getPSID() \ - ((WIZCHIP_READ(PSID) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PSID,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PMRU register - * @param (uint16_t)pmru Value to set @ref PMRU register. - * @sa getPMRU() - */ -#define setPMRU(pmru) { \ - WIZCHIP_WRITE(PMRU, (uint8_t)(pmru>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(PMRU,1), (uint8_t) pmru); \ - } - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PMRU register - * @return uint16_t. Value of @ref PMRU register. - * @sa setPMRU() - */ -#define getPMRU() \ - ((WIZCHIP_READ(PMRU) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(PMRU,1))) - -/** - * @ingroup Common_register_access_function - * @brief Get unreachable IP address - * @param (uint8_t*)uipr Pointer variable to get unreachable IP address. It should be allocated 4 bytes. - */ -#define getUIPR(uipr) \ - WIZCHIP_READ_BUF(UIPR,uipr,6) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref UPORTR register - * @return uint16_t. Value of @ref UPORTR register. - */ -#define getUPORTR() \ - ((WIZCHIP_READ(UPORTR) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(UPORTR,1))) - -/** - * @ingroup Common_register_access_function - * @brief Set @ref PHYCFGR register - * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. - * @sa getPHYCFGR() - */ -#define setPHYCFGR(phycfgr) \ - WIZCHIP_WRITE(PHYCFGR, phycfgr) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref PHYCFGR register - * @return uint8_t. Value of @ref PHYCFGR register. - * @sa setPHYCFGR() - */ -#define getPHYCFGR() \ - WIZCHIP_READ(PHYCFGR) - -/** - * @ingroup Common_register_access_function - * @brief Get @ref VERSIONR register - * @return uint8_t. Value of @ref VERSIONR register. - */ -#define getVERSIONR() \ - WIZCHIP_READ(VERSIONR) - -///////////////////////////////////// - -/////////////////////////////////// -// Socket N register I/O function // -/////////////////////////////////// -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)mr Value to set @ref Sn_MR - * @sa getSn_MR() - */ -#define setSn_MR(sn, mr) \ - WIZCHIP_WRITE(Sn_MR(sn),mr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_MR. - * @sa setSn_MR() - */ -#define getSn_MR(sn) \ - WIZCHIP_READ(Sn_MR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)cr Value to set @ref Sn_CR - * @sa getSn_CR() - */ -#define setSn_CR(sn, cr) \ - WIZCHIP_WRITE(Sn_CR(sn), cr) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_CR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_CR. - * @sa setSn_CR() - */ -#define getSn_CR(sn) \ - WIZCHIP_READ(Sn_CR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ir Value to set @ref Sn_IR - * @sa getSn_IR() - */ -#define setSn_IR(sn, ir) \ - WIZCHIP_WRITE(Sn_IR(sn), (ir & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IR. - * @sa setSn_IR() - */ -#define getSn_IR(sn) \ - (WIZCHIP_READ(Sn_IR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)imr Value to set @ref Sn_IMR - * @sa getSn_IMR() - */ -#define setSn_IMR(sn, imr) \ - WIZCHIP_WRITE(Sn_IMR(sn), (imr & 0x1F)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_IMR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_IMR. - * @sa setSn_IMR() - */ -#define getSn_IMR(sn) \ - (WIZCHIP_READ(Sn_IMR(sn)) & 0x1F) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_SR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_SR. - */ -#define getSn_SR(sn) \ - WIZCHIP_READ(Sn_SR(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)port Value to set @ref Sn_PORT. - * @sa getSn_PORT() - */ -#define setSn_PORT(sn, port) { \ - WIZCHIP_WRITE(Sn_PORT(sn), (uint8_t)(port >> 8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1), (uint8_t) port); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_PORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_PORT. - * @sa setSn_PORT() - */ -#define getSn_PORT(sn) \ - ((WIZCHIP_READ(Sn_PORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_PORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DHAR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. - * @sa getSn_DHAR() - */ -#define setSn_DHAR(sn, dhar) \ - WIZCHIP_WRITE_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. - * @sa setSn_DHAR() - */ -#define getSn_DHAR(sn, dhar) \ - WIZCHIP_READ_BUF(Sn_DHAR(sn), dhar, 6) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. - * @sa getSn_DIPR() - */ -#define setSn_DIPR(sn, dipr) \ - WIZCHIP_WRITE_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DIPR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. - * @sa SetSn_DIPR() - */ -#define getSn_DIPR(sn, dipr) \ - WIZCHIP_READ_BUF(Sn_DIPR(sn), dipr, 4) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)dport Value to set @ref Sn_DPORT - * @sa getSn_DPORT() - */ -#define setSn_DPORT(sn, dport) { \ - WIZCHIP_WRITE(Sn_DPORT(sn), (uint8_t) (dport>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1), (uint8_t) dport); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_DPORT register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_DPORT. - * @sa setSn_DPORT() - */ -#define getSn_DPORT(sn) \ - ((WIZCHIP_READ(Sn_DPORT(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_DPORT(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)mss Value to set @ref Sn_MSSR - * @sa setSn_MSSR() - */ -#define setSn_MSSR(sn, mss) { \ - WIZCHIP_WRITE(Sn_MSSR(sn), (uint8_t)(mss>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1), (uint8_t) mss); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_MSSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_MSSR. - * @sa setSn_MSSR() - */ -#define getSn_MSSR(sn) \ - ((WIZCHIP_READ(Sn_MSSR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_MSSR(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)tos Value to set @ref Sn_TOS - * @sa getSn_TOS() - */ -#define setSn_TOS(sn, tos) \ - WIZCHIP_WRITE(Sn_TOS(sn), tos) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TOS register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of Sn_TOS. - * @sa setSn_TOS() - */ -#define getSn_TOS(sn) \ - WIZCHIP_READ(Sn_TOS(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)ttl Value to set @ref Sn_TTL - * @sa getSn_TTL() - */ -#define setSn_TTL(sn, ttl) \ - WIZCHIP_WRITE(Sn_TTL(sn), ttl) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TTL register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TTL. - * @sa setSn_TTL() - */ -#define getSn_TTL(sn) \ - WIZCHIP_READ(Sn_TTL(sn)) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE - * @sa getSn_RXBUF_SIZE() - */ -#define setSn_RXBUF_SIZE(sn, rxbufsize) \ - WIZCHIP_WRITE(Sn_RXBUF_SIZE(sn),rxbufsize) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. - * @sa setSn_RXBUF_SIZE() - */ -#define getSn_RXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_RXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE - * @sa getSn_TXBUF_SIZE() - */ -#define setSn_TXBUF_SIZE(sn, txbufsize) \ - WIZCHIP_WRITE(Sn_TXBUF_SIZE(sn), txbufsize) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TXBUF_SIZE register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. - * @sa setSn_TXBUF_SIZE() - */ -#define getSn_TXBUF_SIZE(sn) \ - WIZCHIP_READ(Sn_TXBUF_SIZE(sn)) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_FSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_FSR. - */ -uint16_t getSn_TX_FSR(uint8_t sn); - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_RD. - */ -#define getSn_TX_RD(sn) \ - ((WIZCHIP_READ(Sn_TX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)txwr Value to set @ref Sn_TX_WR - * @sa GetSn_TX_WR() - */ -#define setSn_TX_WR(sn, txwr) { \ - WIZCHIP_WRITE(Sn_TX_WR(sn), (uint8_t)(txwr>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1), (uint8_t) txwr); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_TX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_TX_WR. - * @sa setSn_TX_WR() - */ -#define getSn_TX_WR(sn) \ - ((WIZCHIP_READ(Sn_TX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_TX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RSR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_RSR. - */ -uint16_t getSn_RX_RSR(uint8_t sn); - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD - * @sa getSn_RX_RD() - */ -#define setSn_RX_RD(sn, rxrd) { \ - WIZCHIP_WRITE(Sn_RX_RD(sn), (uint8_t)(rxrd>>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1), (uint8_t) rxrd); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_RD register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @regurn uint16_t. Value of @ref Sn_RX_RD. - * @sa setSn_RX_RD() - */ -#define getSn_RX_RD(sn) \ - ((WIZCHIP_READ(Sn_RX_RD(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_RD(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_RX_WR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_RX_WR. - */ -#define getSn_RX_WR(sn) \ - ((WIZCHIP_READ(Sn_RX_WR(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_RX_WR(sn),1))) - - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint16_t)frag Value to set @ref Sn_FRAG - * @sa getSn_FRAD() - */ -#define setSn_FRAG(sn, frag) { \ - WIZCHIP_WRITE(Sn_FRAG(sn), (uint8_t)(frag >>8)); \ - WIZCHIP_WRITE(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1), (uint8_t) frag); \ - } - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_FRAG register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of @ref Sn_FRAG. - * @sa setSn_FRAG() - */ -#define getSn_FRAG(sn) \ - ((WIZCHIP_READ(Sn_FRAG(sn)) << 8) + WIZCHIP_READ(WIZCHIP_OFFSET_INC(Sn_FRAG(sn),1))) - -/** - * @ingroup Socket_register_access_function - * @brief Set @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param (uint8_t)kpalvt Value to set @ref Sn_KPALVTR - * @sa getSn_KPALVTR() - */ -#define setSn_KPALVTR(sn, kpalvt) \ - WIZCHIP_WRITE(Sn_KPALVTR(sn), kpalvt) - -/** - * @ingroup Socket_register_access_function - * @brief Get @ref Sn_KPALVTR register - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint8_t. Value of @ref Sn_KPALVTR. - * @sa setSn_KPALVTR() - */ -#define getSn_KPALVTR(sn) \ - WIZCHIP_READ(Sn_KPALVTR(sn)) - -////////////////////////////////////// - -///////////////////////////////////// -// Sn_TXBUF & Sn_RXBUF IO function // -///////////////////////////////////// -/** - * @brief Gets the max buffer size of socket sn passed as parameter. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n RX max buffer size. - */ -#define getSn_RxMAX(sn) \ - (getSn_RXBUF_SIZE(sn) << 10) - -/** - * @brief Gets the max buffer size of socket sn passed as parameters. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @return uint16_t. Value of Socket n TX max buffer size. - */ -//uint16_t getSn_TxMAX(uint8_t sn); -#define getSn_TxMAX(sn) \ - (getSn_TXBUF_SIZE(sn) << 10) - -/** - * @ingroup Basic_IO_function - * @brief It copies data to internal TX memory - * - * @details This function reads the Tx write pointer register and after that, - * it copies the wizdata(pointer buffer) of the length of len(variable) bytes to internal TX memory - * and updates the Tx write pointer register. - * This function is being called by send() and sendto() function also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to write data - * @param len Data length - * @sa wiz_recv_data() - */ -void wiz_send_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It copies data to your buffer from internal RX memory - * - * @details This function read the Rx read pointer register and after that, - * it copies the received data from internal RX memory - * to wizdata(pointer variable) of the length of len(variable) bytes. - * This function is being called by recv() also. - * - * @note User should read upper byte first and lower byte later to get proper value. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param wizdata Pointer buffer to read data - * @param len Data length - * @sa wiz_send_data() - */ -void wiz_recv_data(uint8_t sn, uint8_t *wizdata, uint16_t len); - -/** - * @ingroup Basic_IO_function - * @brief It discard the received data in RX memory. - * @details It discards the data of the length of len(variable) bytes in internal RX memory. - * @param (uint8_t)sn Socket number. It should be 0 ~ 7. - * @param len Data length - */ -void wiz_recv_ignore(uint8_t sn, uint16_t len); - -#endif // _W5500_H_ diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.c b/drivers/wiznet5k/ethernet/wizchip_conf.c deleted file mode 100644 index c7a2f50f04f73..0000000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.c +++ /dev/null @@ -1,662 +0,0 @@ -//****************************************************************************/ -//! -//! \file wizchip_conf.c -//! \brief WIZCHIP Config Header File. -//! \version 1.0.1 -//! \date 2013/10/21 -//! \par Revision history -//! <2014/05/01> V1.0.1 Refer to M20140501 -//! 1. Explicit type casting in wizchip_bus_readbyte() & wizchip_bus_writebyte() -// Issued by Mathias ClauBen. -//! uint32_t type converts into ptrdiff_t first. And then recoverting it into uint8_t* -//! For remove the warning when pointer type size is not 32bit. -//! If ptrdiff_t doesn't support in your complier, You should must replace ptrdiff_t into your suitable pointer type. -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//*****************************************************************************/ -//A20140501 : for use the type - ptrdiff_t -#include -// - -#include "wizchip_conf.h" -#include "socket.h" - -/** - * @brief Default function to enable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_enter(void) {}; -/** - * @brief Default function to disable interrupt. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cris_exit(void) {}; -/** - * @brief Default function to select chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_select(void) {}; -/** - * @brief Default function to deselect chip. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_cs_deselect(void) {}; -/** - * @brief Default function to read in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - //M20140501 : Explict pointer type casting -//uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *) AddrSel); }; -uint8_t wizchip_bus_readbyte(uint32_t AddrSel) { return * ((volatile uint8_t *)((ptrdiff_t) AddrSel)); }; -/** - * @brief Default function to write in direct or indirect interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ - -//M20140501 : Explict pointer type casting -//void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*) AddrSel) = wb; }; -void wizchip_bus_writebyte(uint32_t AddrSel, uint8_t wb) { *((volatile uint8_t*)((ptrdiff_t)AddrSel)) = wb; }; - -/** - * @brief Default function to read in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_readbytes(uint8_t *buf, uint32_t len) {} -/** - * @brief Default function to write in SPI interface. - * @note This function help not to access wrong address. If you do not describe this function or register any functions, - * null function is called. - */ -void wizchip_spi_writebytes(const uint8_t *buf, uint32_t len) {} - -/** - * @\ref _WIZCHIP instance - */ -_WIZCHIP WIZCHIP = - { - .id = _WIZCHIP_ID_, - .if_mode = _WIZCHIP_IO_MODE_, - .CRIS._enter = wizchip_cris_enter, - .CRIS._exit = wizchip_cris_exit, - .CS._select = wizchip_cs_select, - .CS._deselect = wizchip_cs_deselect, - .IF.BUS._read_byte = wizchip_bus_readbyte, - .IF.BUS._write_byte = wizchip_bus_writebyte -// .IF.SPI._read_byte = wizchip_spi_readbyte, -// .IF.SPI._write_byte = wizchip_spi_writebyte - }; - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -static uint8_t _SUBN_[4]; // subnet -#endif -static uint8_t _DNS_[4]; // DNS server ip address -static dhcp_mode _DHCP_; // DHCP mode - -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)) -{ - if(!cris_en || !cris_ex) - { - WIZCHIP.CRIS._enter = wizchip_cris_enter; - WIZCHIP.CRIS._exit = wizchip_cris_exit; - } - else - { - WIZCHIP.CRIS._enter = cris_en; - WIZCHIP.CRIS._exit = cris_ex; - } -} - -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)) -{ - if(!cs_sel || !cs_desel) - { - WIZCHIP.CS._select = wizchip_cs_select; - WIZCHIP.CS._deselect = wizchip_cs_deselect; - } - else - { - WIZCHIP.CS._select = cs_sel; - WIZCHIP.CS._deselect = cs_desel; - } -} - -void reg_wizchip_bus_cbfunc(uint8_t(*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_BUS_)); - - if(!bus_rb || !bus_wb) - { - WIZCHIP.IF.BUS._read_byte = wizchip_bus_readbyte; - WIZCHIP.IF.BUS._write_byte = wizchip_bus_writebyte; - } - else - { - WIZCHIP.IF.BUS._read_byte = bus_rb; - WIZCHIP.IF.BUS._write_byte = bus_wb; - } -} - -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)) -{ - while(!(WIZCHIP.if_mode & _WIZCHIP_IO_MODE_SPI_)); - - if(!spi_rb || !spi_wb) - { - WIZCHIP.IF.SPI._read_bytes = wizchip_spi_readbytes; - WIZCHIP.IF.SPI._write_bytes = wizchip_spi_writebytes; - } - else - { - WIZCHIP.IF.SPI._read_bytes = spi_rb; - WIZCHIP.IF.SPI._write_bytes = spi_wb; - } -} - -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg) -{ - uint8_t tmp = 0; - uint8_t* ptmp[2] = {0,0}; - switch(cwtype) - { - case CW_RESET_WIZCHIP: - wizchip_sw_reset(); - break; - case CW_INIT_WIZCHIP: - if(arg != 0) - { - ptmp[0] = (uint8_t*)arg; - ptmp[1] = ptmp[0] + _WIZCHIP_SOCK_NUM_; - } - return wizchip_init(ptmp[0], ptmp[1]); - case CW_CLR_INTERRUPT: - wizchip_clrinterrupt(*((intr_kind*)arg)); - break; - case CW_GET_INTERRUPT: - *((intr_kind*)arg) = wizchip_getinterrupt(); - break; - case CW_SET_INTRMASK: - wizchip_setinterruptmask(*((intr_kind*)arg)); - break; - case CW_GET_INTRMASK: - *((intr_kind*)arg) = wizchip_getinterruptmask(); - break; - #if _WIZCHIP_ > 5100 - case CW_SET_INTRTIME: - setINTLEVEL(*(uint16_t*)arg); - break; - case CW_GET_INTRTIME: - *(uint16_t*)arg = getINTLEVEL(); - break; - #endif - case CW_GET_ID: - ((uint8_t*)arg)[0] = WIZCHIP.id[0]; - ((uint8_t*)arg)[1] = WIZCHIP.id[1]; - ((uint8_t*)arg)[2] = WIZCHIP.id[2]; - ((uint8_t*)arg)[3] = WIZCHIP.id[3]; - ((uint8_t*)arg)[4] = WIZCHIP.id[4]; - ((uint8_t*)arg)[5] = 0; - break; - #if _WIZCHIP_ == 5500 - case CW_RESET_PHY: - wizphy_reset(); - break; - case CW_SET_PHYCONF: - wizphy_setphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYCONF: - wizphy_getphyconf((wiz_PhyConf*)arg); - break; - case CW_GET_PHYSTATUS: - break; - case CW_SET_PHYPOWMODE: - return wizphy_setphypmode(*(uint8_t*)arg); - #endif - case CW_GET_PHYPOWMODE: - tmp = wizphy_getphypmode(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - case CW_GET_PHYLINK: - tmp = wizphy_getphylink(); - if((int8_t)tmp == -1) return -1; - *(uint8_t*)arg = tmp; - break; - default: - return -1; - } - return 0; -} - - -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg) -{ - - switch(cntype) - { - case CN_SET_NETINFO: - wizchip_setnetinfo((wiz_NetInfo*)arg); - break; - case CN_GET_NETINFO: - wizchip_getnetinfo((wiz_NetInfo*)arg); - break; - case CN_SET_NETMODE: - return wizchip_setnetmode(*(netmode_type*)arg); - case CN_GET_NETMODE: - *(netmode_type*)arg = wizchip_getnetmode(); - break; - case CN_SET_TIMEOUT: - wizchip_settimeout((wiz_NetTimeout*)arg); - break; - case CN_GET_TIMEOUT: - wizchip_gettimeout((wiz_NetTimeout*)arg); - break; - default: - return -1; - } - return 0; -} - -void wizchip_sw_reset(void) -{ - uint8_t gw[4], sn[4], sip[4]; - uint8_t mac[6]; - getSHAR(mac); - getGAR(gw); getSUBR(sn); getSIPR(sip); - setMR(MR_RST); - getMR(); // for delay - setSHAR(mac); - setGAR(gw); - setSUBR(sn); - setSIPR(sip); -} - -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize) -{ - int8_t i; - int8_t tmp = 0; - wizchip_sw_reset(); - if(txsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += txsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_TXBUF_SIZE(i, txsize[i]); - } - if(rxsize) - { - tmp = 0; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - tmp += rxsize[i]; - if(tmp > 16) return -1; - for(i = 0 ; i < _WIZCHIP_SOCK_NUM_; i++) - setSn_RXBUF_SIZE(i, rxsize[i]); - } - - WIZCHIP_EXPORT(socket_reset)(); - - return 0; -} - -void wizchip_clrinterrupt(intr_kind intr) -{ - uint8_t ir = (uint8_t)intr; - uint8_t sir = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - ir |= (1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir |= (1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - sir &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - ir |= sir; - setIR(ir); -#else - setIR(ir); - setSIR(sir); -#endif -} - -intr_kind wizchip_getinterrupt(void) -{ - uint8_t ir = 0; - uint8_t sir = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - ir = getIR(); - sir = ir 0x0F; -#else - ir = getIR(); - sir = getSIR(); -#endif - -#if _WIZCHIP_ < 5500 - ir &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - ir &= ~(1 << 6); -#endif - ret = sir; - ret = (ret << 8) + ir; - return (intr_kind)ret; -} - -void wizchip_setinterruptmask(intr_kind intr) -{ - uint8_t imr = (uint8_t)intr; - uint8_t simr = (uint8_t)((uint16_t)intr >> 8); -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); -#endif - -#if _WIZCHIP_ < 5200 - simr &= 0x0F; -#endif - -#if _WIZCHIP_ == 5100 - imr |= simr; - setIMR(imr); -#else - setIMR(imr); - setSIMR(simr); -#endif -} - -intr_kind wizchip_getinterruptmask(void) -{ - uint8_t imr = 0; - uint8_t simr = 0; - uint16_t ret = 0; -#if _WIZCHIP_ == 5100 - imr = getIMR(); - simr = imr 0x0F; -#else - imr = getIMR(); - simr = getSIMR(); -#endif - -#if _WIZCHIP_ < 5500 - imr &= ~(1<<4); // IK_WOL -#endif -#if _WIZCHIP_ == 5200 - imr &= ~(1 << 6); // IK_DEST_UNREACH -#endif - ret = simr; - ret = (ret << 8) + imr; - return (intr_kind)ret; -} - -int8_t wizphy_getphylink(void) -{ - int8_t tmp; -#if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_LINK) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_LNK_ON) - tmp = PHY_LINK_ON; - else - tmp = PHY_LINK_OFF; -#else - tmp = -1; -#endif - return tmp; -} - -#if _WIZCHIP_ > 5100 - -int8_t wizphy_getphypmode(void) -{ - int8_t tmp = 0; - #if _WIZCHIP_ == 5200 - if(getPHYSTATUS() & PHYSTATUS_POWERDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #elif _WIZCHIP_ == 5500 - if(getPHYCFGR() & PHYCFGR_OPMDC_PDOWN) - tmp = PHY_POWER_DOWN; - else - tmp = PHY_POWER_NORM; - #else - tmp = -1; - #endif - return tmp; -} -#endif - -#if _WIZCHIP_ == 5500 -void wizphy_reset(void) -{ - uint8_t tmp = getPHYCFGR(); - tmp &= PHYCFGR_RST; - setPHYCFGR(tmp); - tmp = getPHYCFGR(); - tmp |= ~PHYCFGR_RST; - setPHYCFGR(tmp); -} - -void wizphy_setphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - if(phyconf->by == PHY_CONFBY_SW) - tmp |= PHYCFGR_OPMD; - else - tmp &= ~PHYCFGR_OPMD; - if(phyconf->mode == PHY_MODE_AUTONEGO) - tmp |= PHYCFGR_OPMDC_ALLA; - else - { - if(phyconf->duplex == PHY_DUPLEX_FULL) - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100F; - else - tmp |= PHYCFGR_OPMDC_10F; - } - else - { - if(phyconf->speed == PHY_SPEED_100) - tmp |= PHYCFGR_OPMDC_100H; - else - tmp |= PHYCFGR_OPMDC_10H; - } - } - setPHYCFGR(tmp); - wizphy_reset(); -} - -void wizphy_getphyconf(wiz_PhyConf* phyconf) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - phyconf->by = (tmp & PHYCFGR_OPMD) ? PHY_CONFBY_SW : PHY_CONFBY_HW; - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_ALLA: - case PHYCFGR_OPMDC_100FA: - phyconf->mode = PHY_MODE_AUTONEGO; - break; - default: - phyconf->mode = PHY_MODE_MANUAL; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_100H: - phyconf->speed = PHY_SPEED_100; - break; - default: - phyconf->speed = PHY_SPEED_10; - break; - } - switch(tmp & PHYCFGR_OPMDC_ALLA) - { - case PHYCFGR_OPMDC_100FA: - case PHYCFGR_OPMDC_100F: - case PHYCFGR_OPMDC_10F: - phyconf->duplex = PHY_DUPLEX_FULL; - break; - default: - phyconf->duplex = PHY_DUPLEX_HALF; - break; - } -} - -void wizphy_getphystat(wiz_PhyConf* phyconf) -{ - uint8_t tmp = getPHYCFGR(); - phyconf->duplex = (tmp & PHYCFGR_DPX_FULL) ? PHY_DUPLEX_FULL : PHY_DUPLEX_HALF; - phyconf->speed = (tmp & PHYCFGR_SPD_100) ? PHY_SPEED_100 : PHY_SPEED_10; -} - -int8_t wizphy_setphypmode(uint8_t pmode) -{ - uint8_t tmp = 0; - tmp = getPHYCFGR(); - if((tmp & PHYCFGR_OPMD)== 0) return -1; - tmp &= ~PHYCFGR_OPMDC_ALLA; - if( pmode == PHY_POWER_DOWN) - tmp |= PHYCFGR_OPMDC_PDOWN; - else - tmp |= PHYCFGR_OPMDC_ALLA; - setPHYCFGR(tmp); - wizphy_reset(); - tmp = getPHYCFGR(); - if( pmode == PHY_POWER_DOWN) - { - if(tmp & PHYCFGR_OPMDC_PDOWN) return 0; - } - else - { - if(tmp & PHYCFGR_OPMDC_ALLA) return 0; - } - return -1; -} -#endif - - -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo) -{ - setSHAR(pnetinfo->mac); - setGAR(pnetinfo->gw); - setSUBR(pnetinfo->sn); - setSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - _SUBN_[0] = pnetinfo->sn[0]; - _SUBN_[1] = pnetinfo->sn[1]; - _SUBN_[2] = pnetinfo->sn[2]; - _SUBN_[3] = pnetinfo->sn[3]; -#endif - _DNS_[0] = pnetinfo->dns[0]; - _DNS_[1] = pnetinfo->dns[1]; - _DNS_[2] = pnetinfo->dns[2]; - _DNS_[3] = pnetinfo->dns[3]; - _DHCP_ = pnetinfo->dhcp; -} - -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo) -{ - getSHAR(pnetinfo->mac); - getGAR(pnetinfo->gw); - getSUBR(pnetinfo->sn); - getSIPR(pnetinfo->ip); -#if _WIZCHIP_ == 5200 // for W5200 ARP errata - pnetinfo->sn[0] = _SUBN_[0]; - pnetinfo->sn[1] = _SUBN_[1]; - pnetinfo->sn[2] = _SUBN_[2]; - pnetinfo->sn[3] = _SUBN_[3]; -#endif - pnetinfo->dns[0]= _DNS_[0]; - pnetinfo->dns[1]= _DNS_[1]; - pnetinfo->dns[2]= _DNS_[2]; - pnetinfo->dns[3]= _DNS_[3]; - pnetinfo->dhcp = _DHCP_; -} - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void) { - return _SUBN_; -} -#endif - -int8_t wizchip_setnetmode(netmode_type netmode) -{ - uint8_t tmp = 0; -#if _WIZCHIP_ != 5500 - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK)) return -1; -#else - if(netmode & ~(NM_WAKEONLAN | NM_PPPOE | NM_PINGBLOCK | NM_FORCEARP)) return -1; -#endif - tmp = getMR(); - tmp |= (uint8_t)netmode; - setMR(tmp); - return 0; -} - -netmode_type wizchip_getnetmode(void) -{ - return (netmode_type) getMR(); -} - -void wizchip_settimeout(wiz_NetTimeout* nettime) -{ - setRCR(nettime->retry_cnt); - setRTR(nettime->time_100us); -} - -void wizchip_gettimeout(wiz_NetTimeout* nettime) -{ - nettime->retry_cnt = getRCR(); - nettime->time_100us = getRTR(); -} diff --git a/drivers/wiznet5k/ethernet/wizchip_conf.h b/drivers/wiznet5k/ethernet/wizchip_conf.h deleted file mode 100644 index 509ba0668a790..0000000000000 --- a/drivers/wiznet5k/ethernet/wizchip_conf.h +++ /dev/null @@ -1,554 +0,0 @@ -//***************************************************************************** -// -//! \file wizchip_conf.h -//! \brief WIZCHIP Config Header File. -//! \version 1.0.0 -//! \date 2013/10/21 -//! \par Revision history -//! <2013/10/21> 1st Release -//! \author MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -/** - * @defgroup extra_functions 2. WIZnet Extra Functions - * - * @brief These functions is optional function. It could be replaced at WIZCHIP I/O function because they were made by WIZCHIP I/O functions. - * @details There are functions of configuring WIZCHIP, network, interrupt, phy, network information and timer. \n - * - */ - -#ifndef _WIZCHIP_CONF_H_ -#define _WIZCHIP_CONF_H_ - -#include -/** - * @brief Select WIZCHIP. - * @todo You should select one, \b 5100, \b 5200 ,\b 5500 or etc. \n\n - * ex> #define \_WIZCHIP_ 5500 - */ -#ifndef _WIZCHIP_ -#define _WIZCHIP_ 5200 // 5100, 5200, 5500 -#endif - -#define _WIZCHIP_IO_MODE_NONE_ 0x0000 -#define _WIZCHIP_IO_MODE_BUS_ 0x0100 /**< Bus interface mode */ -#define _WIZCHIP_IO_MODE_SPI_ 0x0200 /**< SPI interface mode */ -//#define _WIZCHIP_IO_MODE_IIC_ 0x0400 -//#define _WIZCHIP_IO_MODE_SDIO_ 0x0800 -// Add to -// - -#define _WIZCHIP_IO_MODE_BUS_DIR_ (_WIZCHIP_IO_MODE_BUS_ + 1) /**< BUS interface mode for direct */ -#define _WIZCHIP_IO_MODE_BUS_INDIR_ (_WIZCHIP_IO_MODE_BUS_ + 2) /**< BUS interface mode for indirect */ - -#define _WIZCHIP_IO_MODE_SPI_VDM_ (_WIZCHIP_IO_MODE_SPI_ + 1) /**< SPI interface mode for variable length data*/ -#define _WIZCHIP_IO_MODE_SPI_FDM_ (_WIZCHIP_IO_MODE_SPI_ + 2) /**< SPI interface mode for fixed length data mode*/ - - -#if (_WIZCHIP_ == 5100) - #define _WIZCHIP_ID_ "W5100\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ , @ref \_WIZCHIP_IO_MODE_BUS_DIR_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ - -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_DIR_ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - -#elif (_WIZCHIP_ == 5200) - #define _WIZCHIP_ID_ "W5200\0" -/** - * @brief Define interface mode. - * @todo you should select interface mode as chip. Select one of @ref \_WIZCHIP_IO_MODE_SPI_ or @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ - */ -// #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_BUS_INDIR_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_ - #include "w5200/w5200.h" -#elif (_WIZCHIP_ == 5500) - #define _WIZCHIP_ID_ "W5500\0" - -/** - * @brief Define interface mode. \n - * @todo Should select interface mode as chip. - * - @ref \_WIZCHIP_IO_MODE_SPI_ \n - * -@ref \_WIZCHIP_IO_MODE_SPI_VDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * -@ref \_WIZCHIP_IO_MODE_SPI_FDM_ : Valid only in @ref \_WIZCHIP_ == 5500 \n - * - @ref \_WIZCHIP_IO_MODE_BUS_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_DIR_ \n - * - @ref \_WIZCHIP_IO_MODE_BUS_INDIR_ \n - * - Others will be defined in future. \n\n - * ex> #define \_WIZCHIP_IO_MODE_ \_WIZCHIP_IO_MODE_SPI_VDM_ - * - */ - //#define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_FDM_ - #define _WIZCHIP_IO_MODE_ _WIZCHIP_IO_MODE_SPI_VDM_ - #include "w5500/w5500.h" -#else - #error "Unknown defined _WIZCHIP_. You should define one of 5100, 5200, and 5500 !!!" -#endif - -#ifndef _WIZCHIP_IO_MODE_ - #error "Undefined _WIZCHIP_IO_MODE_. You should define it !!!" -#endif - -/** - * @brief Define I/O base address when BUS IF mode. - * @todo Should re-define it to fit your system when BUS IF Mode (@ref \_WIZCHIP_IO_MODE_BUS_, - * @ref \_WIZCHIP_IO_MODE_BUS_DIR_, @ref \_WIZCHIP_IO_MODE_BUS_INDIR_). \n\n - * ex> #define \_WIZCHIP_IO_BASE_ 0x00008000 - */ -#define _WIZCHIP_IO_BASE_ 0x00000000 // - -#if _WIZCHIP_IO_MODE_ & _WIZCHIP_IO_MODE_BUS_ - #ifndef _WIZCHIP_IO_BASE_ - #error "You should be define _WIZCHIP_IO_BASE to fit your system memory map." - #endif -#endif - -#if _WIZCHIP_ > 5100 - #define _WIZCHIP_SOCK_NUM_ 8 ///< The count of independant socket of @b WIZCHIP -#else - #define _WIZCHIP_SOCK_NUM_ 4 ///< The count of independant socket of @b WIZCHIP -#endif - - -/******************************************************** -* WIZCHIP BASIC IF functions for SPI, SDIO, I2C , ETC. -*********************************************************/ -/** - * @ingroup DATA_TYPE - * @brief The set of callback functions for W5500:@ref WIZCHIP_IO_Functions W5200:@ref WIZCHIP_IO_Functions_W5200 - */ -typedef struct __WIZCHIP -{ - uint16_t if_mode; ///< host interface mode - uint8_t id[6]; ///< @b WIZCHIP ID such as @b 5100, @b 5200, @b 5500, and so on. - /** - * The set of critical section callback func. - */ - struct _CRIS - { - void (*_enter) (void); ///< crtical section enter - void (*_exit) (void); ///< critial section exit - }CRIS; - /** - * The set of @ref\_WIZCHIP_ select control callback func. - */ - struct _CS - { - void (*_select) (void); ///< @ref \_WIZCHIP_ selected - void (*_deselect)(void); ///< @ref \_WIZCHIP_ deselected - }CS; - /** - * The set of interface IO callback func. - */ - union _IF - { - /** - * For BUS interface IO - */ - struct - { - uint8_t (*_read_byte) (uint32_t AddrSel); - void (*_write_byte) (uint32_t AddrSel, uint8_t wb); - }BUS; - /** - * For SPI interface IO - */ - struct - { - void (*_read_bytes) (uint8_t *buf, uint32_t len); - void (*_write_bytes) (const uint8_t *buf, uint32_t len); - }SPI; - // To be added - // - }IF; -}_WIZCHIP; - -extern _WIZCHIP WIZCHIP; - -/** - * @ingroup DATA_TYPE - * WIZCHIP control type enumration used in @ref ctlwizchip(). - */ -typedef enum -{ - CW_RESET_WIZCHIP, ///< Resets WIZCHIP by softly - CW_INIT_WIZCHIP, ///< Inializes to WIZCHIP with SOCKET buffer size 2 or 1 dimension array typed uint8_t. - CW_GET_INTERRUPT, ///< Get Interrupt status of WIZCHIP - CW_CLR_INTERRUPT, ///< Clears interrupt - CW_SET_INTRMASK, ///< Masks interrupt - CW_GET_INTRMASK, ///< Get interrupt mask - CW_SET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_INTRTIME, ///< Set interval time between the current and next interrupt. - CW_GET_ID, ///< Gets WIZCHIP name. - -#if _WIZCHIP_ == 5500 - CW_RESET_PHY, ///< Resets internal PHY. Valid Only W5000 - CW_SET_PHYCONF, ///< When PHY configured by interal register, PHY operation mode (Manual/Auto, 10/100, Half/Full). Valid Only W5000 - CW_GET_PHYCONF, ///< Get PHY operation mode in interal register. Valid Only W5000 - CW_GET_PHYSTATUS, ///< Get real PHY status on operating. Valid Only W5000 - CW_SET_PHYPOWMODE, ///< Set PHY power mode as noraml and down when PHYSTATUS.OPMD == 1. Valid Only W5000 -#endif - CW_GET_PHYPOWMODE, ///< Get PHY Power mode as down or normal - CW_GET_PHYLINK ///< Get PHY Link status -}ctlwizchip_type; - -/** - * @ingroup DATA_TYPE - * Network control type enumration used in @ref ctlnetwork(). - */ -typedef enum -{ - CN_SET_NETINFO, ///< Set Network with @ref wiz_NetInfo - CN_GET_NETINFO, ///< Get Network with @ref wiz_NetInfo - CN_SET_NETMODE, ///< Set network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_GET_NETMODE, ///< Get network mode as WOL, PPPoE, Ping Block, and Force ARP mode - CN_SET_TIMEOUT, ///< Set network timeout as retry count and time. - CN_GET_TIMEOUT, ///< Get network timeout as retry count and time. -}ctlnetwork_type; - -/** - * @ingroup DATA_TYPE - * Interrupt kind when CW_SET_INTRRUPT, CW_GET_INTERRUPT, CW_SET_INTRMASK - * and CW_GET_INTRMASK is used in @ref ctlnetwork(). - * It can be used with OR operation. - */ -typedef enum -{ -#if _WIZCHIP_ > 5200 - IK_WOL = (1 << 4), ///< Wake On Lan by receiving the magic packet. Valid in W500. -#endif - - IK_PPPOE_TERMINATED = (1 << 5), ///< PPPoE Disconnected - -#if _WIZCHIP_ != 5200 - IK_DEST_UNREACH = (1 << 6), ///< Destination IP & Port Unreable, No use in W5200 -#endif - - IK_IP_CONFLICT = (1 << 7), ///< IP conflict occurred - - IK_SOCK_0 = (1 << 8), ///< Socket 0 interrupt - IK_SOCK_1 = (1 << 9), ///< Socket 1 interrupt - IK_SOCK_2 = (1 << 10), ///< Socket 2 interrupt - IK_SOCK_3 = (1 << 11), ///< Socket 3 interrupt -#if _WIZCHIP_ > 5100 - IK_SOCK_4 = (1 << 12), ///< Socket 4 interrupt, No use in 5100 - IK_SOCK_5 = (1 << 13), ///< Socket 5 interrupt, No use in 5100 - IK_SOCK_6 = (1 << 14), ///< Socket 6 interrupt, No use in 5100 - IK_SOCK_7 = (1 << 15), ///< Socket 7 interrupt, No use in 5100 -#endif - -#if _WIZCHIP_ > 5100 - IK_SOCK_ALL = (0xFF << 8) ///< All Socket interrpt -#else - IK_SOCK_ALL = (0x0F << 8) ///< All Socket interrpt -#endif -}intr_kind; - -#define PHY_CONFBY_HW 0 ///< Configured PHY operation mode by HW pin -#define PHY_CONFBY_SW 1 ///< Configured PHY operation mode by SW register -#define PHY_MODE_MANUAL 0 ///< Configured PHY operation mode with user setting. -#define PHY_MODE_AUTONEGO 1 ///< Configured PHY operation mode with auto-negotiation -#define PHY_SPEED_10 0 ///< Link Speed 10 -#define PHY_SPEED_100 1 ///< Link Speed 100 -#define PHY_DUPLEX_HALF 0 ///< Link Half-Duplex -#define PHY_DUPLEX_FULL 1 ///< Link Full-Duplex -#define PHY_LINK_OFF 0 ///< Link Off -#define PHY_LINK_ON 1 ///< Link On -#define PHY_POWER_NORM 0 ///< PHY power normal mode -#define PHY_POWER_DOWN 1 ///< PHY power down mode - - -#if _WIZCHIP_ == 5500 -/** - * @ingroup DATA_TYPE - * It configures PHY configuration when CW_SET PHYCONF or CW_GET_PHYCONF in W5500, - * and it indicates the real PHY status configured by HW or SW in all WIZCHIP. \n - * Valid only in W5500. - */ -typedef struct wiz_PhyConf_t -{ - uint8_t by; ///< set by @ref PHY_CONFBY_HW or @ref PHY_CONFBY_SW - uint8_t mode; ///< set by @ref PHY_MODE_MANUAL or @ref PHY_MODE_AUTONEGO - uint8_t speed; ///< set by @ref PHY_SPEED_10 or @ref PHY_SPEED_100 - uint8_t duplex; ///< set by @ref PHY_DUPLEX_HALF @ref PHY_DUPLEX_FULL - //uint8_t power; ///< set by @ref PHY_POWER_NORM or @ref PHY_POWER_DOWN - //uint8_t link; ///< Valid only in CW_GET_PHYSTATUS. set by @ref PHY_LINK_ON or PHY_DUPLEX_OFF - }wiz_PhyConf; -#endif - -/** - * @ingroup DATA_TYPE - * It used in setting dhcp_mode of @ref wiz_NetInfo. - */ -typedef enum -{ - NETINFO_STATIC = 1, ///< Static IP configuration by manually. - NETINFO_DHCP ///< Dynamic IP configruation from a DHCP sever -}dhcp_mode; - -/** - * @ingroup DATA_TYPE - * Network Information for WIZCHIP - */ -typedef struct wiz_NetInfo_t -{ - uint8_t mac[6]; ///< Source Mac Address - uint8_t ip[4]; ///< Source IP Address - uint8_t sn[4]; ///< Subnet Mask - uint8_t gw[4]; ///< Gateway IP Address - uint8_t dns[4]; ///< DNS server IP Address - dhcp_mode dhcp; ///< 1 - Static, 2 - DHCP -}wiz_NetInfo; - -/** - * @ingroup DATA_TYPE - * Network mode - */ -typedef enum -{ -#if _WIZCHIP_ == 5500 - NM_FORCEARP = (1<<1), ///< Force to APP send whenever udp data is sent. Valid only in W5500 -#endif - NM_WAKEONLAN = (1<<5), ///< Wake On Lan - NM_PINGBLOCK = (1<<4), ///< Block ping-request - NM_PPPOE = (1<<3), ///< PPPoE mode -}netmode_type; - -/** - * @ingroup DATA_TYPE - * Used in CN_SET_TIMEOUT or CN_GET_TIMEOUT of @ref ctlwizchip() for timeout configruation. - */ -typedef struct wiz_NetTimeout_t -{ - uint8_t retry_cnt; ///< retry count - uint16_t time_100us; ///< time unit 100us -}wiz_NetTimeout; - -/** - *@brief Registers call back function for critical section of I/O functions such as - *\ref WIZCHIP_READ, @ref WIZCHIP_WRITE, @ref WIZCHIP_READ_BUF and @ref WIZCHIP_WRITE_BUF. - *@param cris_en : callback function for critical section enter. - *@param cris_ex : callback function for critical section exit. - *@todo Describe @ref WIZCHIP_CRITICAL_ENTER and @ref WIZCHIP_CRITICAL_EXIT marco or register your functions. - *@note If you do not describe or register, default functions(@ref wizchip_cris_enter & @ref wizchip_cris_exit) is called. - */ -void reg_wizchip_cris_cbfunc(void(*cris_en)(void), void(*cris_ex)(void)); - - -/** - *@brief Registers call back function for WIZCHIP select & deselect. - *@param cs_sel : callback function for WIZCHIP select - *@param cs_desel : callback fucntion for WIZCHIP deselect - *@todo Describe @ref wizchip_cs_select and @ref wizchip_cs_deselect function or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_cs_cbfunc(void(*cs_sel)(void), void(*cs_desel)(void)); - -/** - *@brief Registers call back function for bus interface. - *@param bus_rb : callback function to read byte data using system bus - *@param bus_wb : callback function to write byte data using system bus - *@todo Describe @ref wizchip_bus_readbyte and @ref wizchip_bus_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_bus_cbfunc(uint8_t (*bus_rb)(uint32_t addr), void (*bus_wb)(uint32_t addr, uint8_t wb)); - -/** - *@brief Registers call back function for SPI interface. - *@param spi_rb : callback function to read byte usig SPI - *@param spi_wb : callback function to write byte usig SPI - *@todo Describe \ref wizchip_spi_readbyte and \ref wizchip_spi_writebyte function - *or register your functions. - *@note If you do not describe or register, null function is called. - */ -void reg_wizchip_spi_cbfunc(void (*spi_rb)(uint8_t *, uint32_t), void (*spi_wb)(const uint8_t *, uint32_t)); - -/** - * @ingroup extra_functions - * @brief Controls to the WIZCHIP. - * @details Resets WIZCHIP & internal PHY, Configures PHY mode, Monitor PHY(Link,Speed,Half/Full/Auto), - * controls interrupt & mask and so on. - * @param cwtype : Decides to the control type - * @param arg : arg type is dependent on cwtype. - * @return 0 : Success \n - * -1 : Fail because of invalid \ref ctlwizchip_type or unsupported \ref ctlwizchip_type in WIZCHIP - */ -int8_t ctlwizchip(ctlwizchip_type cwtype, void* arg); - -/** - * @ingroup extra_functions - * @brief Controls to network. - * @details Controls to network environment, mode, timeout and so on. - * @param cntype : Input. Decides to the control type - * @param arg : Inout. arg type is dependent on cntype. - * @return -1 : Fail because of invalid \ref ctlnetwork_type or unsupported \ref ctlnetwork_type in WIZCHIP \n - * 0 : Success - */ -int8_t ctlnetwork(ctlnetwork_type cntype, void* arg); - - -/* - * The following functions are implemented for internal use. - * but You can call these functions for code size reduction instead of ctlwizchip() and ctlnetwork(). - */ - -/** - * @ingroup extra_functions - * @brief Reset WIZCHIP by softly. - */ -void wizchip_sw_reset(void); - -/** - * @ingroup extra_functions - * @brief Initializes WIZCHIP with socket buffer size - * @param txsize Socket tx buffer sizes. If null, initialized the default size 2KB. - * @param rxsize Socket rx buffer sizes. If null, initialized the default size 2KB. - * @return 0 : succcess \n - * -1 : fail. Invalid buffer size - */ -int8_t wizchip_init(uint8_t* txsize, uint8_t* rxsize); - -/** - * @ingroup extra_functions - * @brief Clear Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_clrinterrupt(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt of WIZCHIP. - * @return @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterrupt(void); - -/** - * @ingroup extra_functions - * @brief Mask or Unmask Interrupt of WIZCHIP. - * @param intr : @ref intr_kind value operated OR. It can type-cast to uint16_t. - */ -void wizchip_setinterruptmask(intr_kind intr); - -/** - * @ingroup extra_functions - * @brief Get Interrupt mask of WIZCHIP. - * @return : The operated OR vaule of @ref intr_kind. It can type-cast to uint16_t. - */ -intr_kind wizchip_getinterruptmask(void); - -#if _WIZCHIP_ > 5100 - int8_t wizphy_getphylink(void); ///< get the link status of phy in WIZCHIP. No use in W5100 - int8_t wizphy_getphypmode(void); ///< get the power mode of PHY in WIZCHIP. No use in W5100 -#endif - -#if _WIZCHIP_ == 5500 - void wizphy_reset(void); ///< Reset phy. Vailid only in W5500 -/** - * @ingroup extra_functions - * @brief Set the phy information for WIZCHIP without power mode - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_setphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy configuration information. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphyconf(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief Get phy status. - * @param phyconf : @ref wiz_PhyConf - */ - void wizphy_getphystat(wiz_PhyConf* phyconf); - /** - * @ingroup extra_functions - * @brief set the power mode of phy inside WIZCHIP. Refer to @ref PHYCFGR in W5500, @ref PHYSTATUS in W5200 - * @param pmode Settig value of power down mode. - */ - int8_t wizphy_setphypmode(uint8_t pmode); -#endif - -/** -* @ingroup extra_functions - * @brief Set the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_setnetinfo(wiz_NetInfo* pnetinfo); - -/** - * @ingroup extra_functions - * @brief Get the network information for WIZCHIP - * @param pnetinfo : @ref wizNetInfo - */ -void wizchip_getnetinfo(wiz_NetInfo* pnetinfo); - -#if _WIZCHIP_ == 5200 // for W5200 ARP errata -uint8_t *wizchip_getsubn(void); -#endif - -/** - * @ingroup extra_functions - * @brief Set the network mode such WOL, PPPoE, Ping Block, and etc. - * @param pnetinfo Value of network mode. Refer to @ref netmode_type. - */ -int8_t wizchip_setnetmode(netmode_type netmode); - -/** - * @ingroup extra_functions - * @brief Get the network mode such WOL, PPPoE, Ping Block, and etc. - * @return Value of network mode. Refer to @ref netmode_type. - */ -netmode_type wizchip_getnetmode(void); - -/** - * @ingroup extra_functions - * @brief Set retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_settimeout(wiz_NetTimeout* nettime); - -/** - * @ingroup extra_functions - * @brief Get retry time value(@ref RTR) and retry count(@ref RCR). - * @details @ref RTR configures the retransmission timeout period and @ref RCR configures the number of time of retransmission. - * @param nettime @ref RTR value and @ref RCR value. Refer to @ref wiz_NetTimeout. - */ -void wizchip_gettimeout(wiz_NetTimeout* nettime); - -#endif // _WIZCHIP_CONF_H_ diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.c b/drivers/wiznet5k/internet/dhcp/dhcp.c deleted file mode 100644 index 00f41c3c7239c..0000000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.c +++ /dev/null @@ -1,975 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.c -//! \brief DHCP APIs implement file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2018/10/09> Modified by Nick Moore for CircuitPython -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Optimize code -//! 2. Add reg_dhcp_cbfunc() -//! 3. Add DHCP_stop() -//! 4. Integrate check_DHCP_state() & DHCP_run() to DHCP_run() -//! 5. Don't care system endian -//! 6. Add comments -//! <2012/12/26> V1.1.1 -//! 1. Modify variable declaration: dhcp_tick_1s is declared volatile for code optimization -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -//#include "Ethernet/socket.h" -//#include "Internet/DHCP/dhcp.h" -#include "../../ethernet/socket.h" -#include "dhcp.h" - -/* If you want to display debug & processing message, Define _DHCP_DEBUG_ in dhcp.h */ - -#ifdef _DHCP_DEBUG_ - #include -#endif - -/* DHCP state machine. */ -#define STATE_DHCP_INIT 0 ///< Initialize -#define STATE_DHCP_DISCOVER 1 ///< send DISCOVER and wait OFFER -#define STATE_DHCP_REQUEST 2 ///< send REQEUST and wait ACK or NACK -#define STATE_DHCP_LEASED 3 ///< ReceiveD ACK and IP leased -#define STATE_DHCP_REREQUEST 4 ///< send REQUEST for maintaining leased IP -#define STATE_DHCP_RELEASE 5 ///< No use -#define STATE_DHCP_STOP 6 ///< Stop processing DHCP - -#define DHCP_FLAGSBROADCAST 0x8000 ///< The broadcast value of flags in @ref RIP_MSG -#define DHCP_FLAGSUNICAST 0x0000 ///< The unicast value of flags in @ref RIP_MSG - -/* DHCP message OP code */ -#define DHCP_BOOTREQUEST 1 ///< Request Message used in op of @ref RIP_MSG -#define DHCP_BOOTREPLY 2 ///< Reply Message used i op of @ref RIP_MSG - -/* DHCP message type */ -#define DHCP_DISCOVER 1 ///< DISCOVER message in OPT of @ref RIP_MSG -#define DHCP_OFFER 2 ///< OFFER message in OPT of @ref RIP_MSG -#define DHCP_REQUEST 3 ///< REQUEST message in OPT of @ref RIP_MSG -#define DHCP_DECLINE 4 ///< DECLINE message in OPT of @ref RIP_MSG -#define DHCP_ACK 5 ///< ACK message in OPT of @ref RIP_MSG -#define DHCP_NAK 6 ///< NACK message in OPT of @ref RIP_MSG -#define DHCP_RELEASE 7 ///< RELEASE message in OPT of @ref RIP_MSG. No use -#define DHCP_INFORM 8 ///< INFORM message in OPT of @ref RIP_MSG. No use - -#define DHCP_HTYPE10MB 1 ///< Used in type of @ref RIP_MSG -#define DHCP_HTYPE100MB 2 ///< Used in type of @ref RIP_MSG - -#define DHCP_HLENETHERNET 6 ///< Used in hlen of @ref RIP_MSG -#define DHCP_HOPS 0 ///< Used in hops of @ref RIP_MSG -#define DHCP_SECS 0 ///< Used in secs of @ref RIP_MSG - -#define INFINITE_LEASETIME 0xffffffff ///< Infinite lease time - -#define OPT_SIZE 312 /// Max OPT size of @ref RIP_MSG -#define RIP_MSG_SIZE (236+OPT_SIZE) /// Max size of @ref RIP_MSG - -/* - * @brief DHCP option and value (cf. RFC1533) - */ -enum -{ - padOption = 0, - subnetMask = 1, - timerOffset = 2, - routersOnSubnet = 3, - timeServer = 4, - nameServer = 5, - dns = 6, - logServer = 7, - cookieServer = 8, - lprServer = 9, - impressServer = 10, - resourceLocationServer = 11, - hostName = 12, - bootFileSize = 13, - meritDumpFile = 14, - domainName = 15, - swapServer = 16, - rootPath = 17, - extentionsPath = 18, - IPforwarding = 19, - nonLocalSourceRouting = 20, - policyFilter = 21, - maxDgramReasmSize = 22, - defaultIPTTL = 23, - pathMTUagingTimeout = 24, - pathMTUplateauTable = 25, - ifMTU = 26, - allSubnetsLocal = 27, - broadcastAddr = 28, - performMaskDiscovery = 29, - maskSupplier = 30, - performRouterDiscovery = 31, - routerSolicitationAddr = 32, - staticRoute = 33, - trailerEncapsulation = 34, - arpCacheTimeout = 35, - ethernetEncapsulation = 36, - tcpDefaultTTL = 37, - tcpKeepaliveInterval = 38, - tcpKeepaliveGarbage = 39, - nisDomainName = 40, - nisServers = 41, - ntpServers = 42, - vendorSpecificInfo = 43, - netBIOSnameServer = 44, - netBIOSdgramDistServer = 45, - netBIOSnodeType = 46, - netBIOSscope = 47, - xFontServer = 48, - xDisplayManager = 49, - dhcpRequestedIPaddr = 50, - dhcpIPaddrLeaseTime = 51, - dhcpOptionOverload = 52, - dhcpMessageType = 53, - dhcpServerIdentifier = 54, - dhcpParamRequest = 55, - dhcpMsg = 56, - dhcpMaxMsgSize = 57, - dhcpT1value = 58, - dhcpT2value = 59, - dhcpClassIdentifier = 60, - dhcpClientIdentifier = 61, - endOption = 255 -}; - -/* - * @brief DHCP message format - */ -typedef struct { - uint8_t op; ///< @ref DHCP_BOOTREQUEST or @ref DHCP_BOOTREPLY - uint8_t htype; ///< @ref DHCP_HTYPE10MB or @ref DHCP_HTYPE100MB - uint8_t hlen; ///< @ref DHCP_HLENETHERNET - uint8_t hops; ///< @ref DHCP_HOPS - uint32_t xid; ///< @ref DHCP_XID This increase one every DHCP transaction. - uint16_t secs; ///< @ref DHCP_SECS - uint16_t flags; ///< @ref DHCP_FLAGSBROADCAST or @ref DHCP_FLAGSUNICAST - uint8_t ciaddr[4]; ///< @ref Request IP to DHCP sever - uint8_t yiaddr[4]; ///< @ref Offered IP from DHCP server - uint8_t siaddr[4]; ///< No use - uint8_t giaddr[4]; ///< No use - uint8_t chaddr[16]; ///< DHCP client 6bytes MAC address. Others is filled to zero - uint8_t sname[64]; ///< No use - uint8_t file[128]; ///< No use - uint8_t OPT[OPT_SIZE]; ///< Option -} RIP_MSG; - - - -uint8_t DHCP_SOCKET; // Socket number for DHCP - -uint8_t DHCP_SIP[4]; // DHCP Server IP address - -// Network information from DHCP Server -uint8_t OLD_allocated_ip[4] = {0, }; // Previous IP address -uint8_t DHCP_allocated_ip[4] = {0, }; // IP address from DHCP -uint8_t DHCP_allocated_gw[4] = {0, }; // Gateway address from DHCP -uint8_t DHCP_allocated_sn[4] = {0, }; // Subnet mask from DHCP -uint8_t DHCP_allocated_dns[4] = {0, }; // DNS address from DHCP - - -int8_t dhcp_state = STATE_DHCP_INIT; // DHCP state -int8_t dhcp_retry_count = 0; - -uint32_t dhcp_lease_time = INFINITE_LEASETIME; -volatile uint32_t dhcp_tick_1s = 0; // unit 1 second -uint32_t dhcp_tick_next = DHCP_WAIT_TIME ; - -uint32_t DHCP_XID; // Any number - -RIP_MSG* pDHCPMSG; // Buffer pointer for DHCP processing - -uint8_t HOST_NAME[] = DCHP_HOST_NAME; - -uint8_t DHCP_CHADDR[6]; // DHCP Client MAC address. - -/* The default callback function */ -void default_ip_assign(void); -void default_ip_update(void); -void default_ip_conflict(void); - -/* Callback handler */ -void (*dhcp_ip_assign)(void) = default_ip_assign; /* handler to be called when the IP address from DHCP server is first assigned */ -void (*dhcp_ip_update)(void) = default_ip_update; /* handler to be called when the IP address from DHCP server is updated */ -void (*dhcp_ip_conflict)(void) = default_ip_conflict; /* handler to be called when the IP address from DHCP server is conflict */ - -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - - -/* send DISCOVER message to DHCP server */ -void send_DHCP_DISCOVER(void); - -/* send REQEUST message to DHCP server */ -void send_DHCP_REQUEST(void); - -/* send DECLINE message to DHCP server */ -void send_DHCP_DECLINE(void); - -/* IP conflict check by sending ARP-request to leased IP and wait ARP-response. */ -int8_t check_DHCP_leasedIP(void); - -/* check the timeout in DHCP process */ -uint8_t check_DHCP_timeout(void); - -/* Intialize to timeout process. */ -void reset_DHCP_timeout(void); - -/* Parse message as OFFER and ACK and NACK from DHCP server.*/ -int8_t parseDHCPCMSG(void); - -/* The default handler of ip assign first */ -void default_ip_assign(void) -{ - setSIPR(DHCP_allocated_ip); - setSUBR(DHCP_allocated_sn); - setGAR (DHCP_allocated_gw); -} - -/* The default handler of ip changed */ -void default_ip_update(void) -{ - /* WIZchip Software Reset */ - setMR(MR_RST); - getMR(); // for delay - default_ip_assign(); - setSHAR(DHCP_CHADDR); -} - -/* The default handler of ip changed */ -void default_ip_conflict(void) -{ - // WIZchip Software Reset - setMR(MR_RST); - getMR(); // for delay - setSHAR(DHCP_CHADDR); -} - -/* register the call back func. */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)) -{ - dhcp_ip_assign = default_ip_assign; - dhcp_ip_update = default_ip_update; - dhcp_ip_conflict = default_ip_conflict; - if(ip_assign) dhcp_ip_assign = ip_assign; - if(ip_update) dhcp_ip_update = ip_update; - if(ip_conflict) dhcp_ip_conflict = ip_conflict; -} - -/* make the common DHCP message */ -void makeDHCPMSG(void) -{ - uint8_t bk_mac[6]; - uint8_t* ptmp; - uint8_t i; - getSHAR(bk_mac); - pDHCPMSG->op = DHCP_BOOTREQUEST; - pDHCPMSG->htype = DHCP_HTYPE10MB; - pDHCPMSG->hlen = DHCP_HLENETHERNET; - pDHCPMSG->hops = DHCP_HOPS; - ptmp = (uint8_t*)(&pDHCPMSG->xid); - *(ptmp+0) = (uint8_t)((DHCP_XID & 0xFF000000) >> 24); - *(ptmp+1) = (uint8_t)((DHCP_XID & 0x00FF0000) >> 16); - *(ptmp+2) = (uint8_t)((DHCP_XID & 0x0000FF00) >> 8); - *(ptmp+3) = (uint8_t)((DHCP_XID & 0x000000FF) >> 0); - pDHCPMSG->secs = DHCP_SECS; - ptmp = (uint8_t*)(&pDHCPMSG->flags); - *(ptmp+0) = (uint8_t)((DHCP_FLAGSBROADCAST & 0xFF00) >> 8); - *(ptmp+1) = (uint8_t)((DHCP_FLAGSBROADCAST & 0x00FF) >> 0); - - pDHCPMSG->ciaddr[0] = 0; - pDHCPMSG->ciaddr[1] = 0; - pDHCPMSG->ciaddr[2] = 0; - pDHCPMSG->ciaddr[3] = 0; - - pDHCPMSG->yiaddr[0] = 0; - pDHCPMSG->yiaddr[1] = 0; - pDHCPMSG->yiaddr[2] = 0; - pDHCPMSG->yiaddr[3] = 0; - - pDHCPMSG->siaddr[0] = 0; - pDHCPMSG->siaddr[1] = 0; - pDHCPMSG->siaddr[2] = 0; - pDHCPMSG->siaddr[3] = 0; - - pDHCPMSG->giaddr[0] = 0; - pDHCPMSG->giaddr[1] = 0; - pDHCPMSG->giaddr[2] = 0; - pDHCPMSG->giaddr[3] = 0; - - pDHCPMSG->chaddr[0] = DHCP_CHADDR[0]; - pDHCPMSG->chaddr[1] = DHCP_CHADDR[1]; - pDHCPMSG->chaddr[2] = DHCP_CHADDR[2]; - pDHCPMSG->chaddr[3] = DHCP_CHADDR[3]; - pDHCPMSG->chaddr[4] = DHCP_CHADDR[4]; - pDHCPMSG->chaddr[5] = DHCP_CHADDR[5]; - - for (i = 6; i < 16; i++) pDHCPMSG->chaddr[i] = 0; - for (i = 0; i < 64; i++) pDHCPMSG->sname[i] = 0; - for (i = 0; i < 128; i++) pDHCPMSG->file[i] = 0; - - // MAGIC_COOKIE - pDHCPMSG->OPT[0] = (uint8_t)((MAGIC_COOKIE & 0xFF000000) >> 24); - pDHCPMSG->OPT[1] = (uint8_t)((MAGIC_COOKIE & 0x00FF0000) >> 16); - pDHCPMSG->OPT[2] = (uint8_t)((MAGIC_COOKIE & 0x0000FF00) >> 8); - pDHCPMSG->OPT[3] = (uint8_t) (MAGIC_COOKIE & 0x000000FF) >> 0; -} - -/* SEND DHCP DISCOVER */ -void send_DHCP_DISCOVER(void) -{ - uint16_t i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DISCOVER; - - // Client identifier - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // fill zero length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x06; // length of request - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - // send broadcasting packet - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_DISCOVER\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* SEND DHCP REQUEST */ -void send_DHCP_REQUEST(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - if(dhcp_state == STATE_DHCP_LEASED || dhcp_state == STATE_DHCP_REREQUEST) - { - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - pDHCPMSG->ciaddr[0] = DHCP_allocated_ip[0]; - pDHCPMSG->ciaddr[1] = DHCP_allocated_ip[1]; - pDHCPMSG->ciaddr[2] = DHCP_allocated_ip[2]; - pDHCPMSG->ciaddr[3] = DHCP_allocated_ip[3]; - ip[0] = DHCP_SIP[0]; - ip[1] = DHCP_SIP[1]; - ip[2] = DHCP_SIP[2]; - ip[3] = DHCP_SIP[3]; - } - else - { - ip[0] = 255; - ip[1] = 255; - ip[2] = 255; - ip[3] = 255; - } - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_REQUEST; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - if(ip[3] == 255) // if(dchp_state == STATE_DHCP_LEASED || dchp_state == DHCP_REREQUEST_STATE) - { - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - } - - // host name - pDHCPMSG->OPT[k++] = hostName; - pDHCPMSG->OPT[k++] = 0; // length of hostname - for(i = 0 ; HOST_NAME[i] != 0; i++) - pDHCPMSG->OPT[k++] = HOST_NAME[i]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - pDHCPMSG->OPT[k - (i+3+1)] = i+3; // length of hostname - - pDHCPMSG->OPT[k++] = dhcpParamRequest; - pDHCPMSG->OPT[k++] = 0x08; - pDHCPMSG->OPT[k++] = subnetMask; - pDHCPMSG->OPT[k++] = routersOnSubnet; - pDHCPMSG->OPT[k++] = dns; - pDHCPMSG->OPT[k++] = domainName; - pDHCPMSG->OPT[k++] = dhcpT1value; - pDHCPMSG->OPT[k++] = dhcpT2value; - pDHCPMSG->OPT[k++] = performRouterDiscovery; - pDHCPMSG->OPT[k++] = staticRoute; - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - -#ifdef _DHCP_DEBUG_ - printf("> Send DHCP_REQUEST\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); - -} - -/* SEND DHCP DHCPDECLINE */ -void send_DHCP_DECLINE(void) -{ - int i; - uint8_t ip[4]; - uint16_t k = 0; - - makeDHCPMSG(); - - k = 4; // because MAGIC_COOKIE already made by makeDHCPMSG() - - *((uint8_t*)(&pDHCPMSG->flags)) = ((DHCP_FLAGSUNICAST & 0xFF00)>> 8); - *((uint8_t*)(&pDHCPMSG->flags)+1) = (DHCP_FLAGSUNICAST & 0x00FF); - - // Option Request Param. - pDHCPMSG->OPT[k++] = dhcpMessageType; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_DECLINE; - - pDHCPMSG->OPT[k++] = dhcpClientIdentifier; - pDHCPMSG->OPT[k++] = 0x07; - pDHCPMSG->OPT[k++] = 0x01; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[0]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[1]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[2]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[3]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[4]; - pDHCPMSG->OPT[k++] = DHCP_CHADDR[5]; - - pDHCPMSG->OPT[k++] = dhcpRequestedIPaddr; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[0]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[1]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[2]; - pDHCPMSG->OPT[k++] = DHCP_allocated_ip[3]; - - pDHCPMSG->OPT[k++] = dhcpServerIdentifier; - pDHCPMSG->OPT[k++] = 0x04; - pDHCPMSG->OPT[k++] = DHCP_SIP[0]; - pDHCPMSG->OPT[k++] = DHCP_SIP[1]; - pDHCPMSG->OPT[k++] = DHCP_SIP[2]; - pDHCPMSG->OPT[k++] = DHCP_SIP[3]; - - pDHCPMSG->OPT[k++] = endOption; - - for (i = k; i < OPT_SIZE; i++) pDHCPMSG->OPT[i] = 0; - - //send broadcasting packet - ip[0] = 0xFF; - ip[1] = 0xFF; - ip[2] = 0xFF; - ip[3] = 0xFF; - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Send DHCP_DECLINE\r\n"); -#endif - - WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, RIP_MSG_SIZE, ip, DHCP_SERVER_PORT); -} - -/* PARSE REPLY pDHCPMSG */ -int8_t parseDHCPMSG(void) -{ - uint8_t svr_addr[6]; - uint16_t svr_port; - uint16_t len; - - uint8_t * p; - uint8_t * e; - uint8_t type = 0; - uint8_t opt_len; - - if((len = getSn_RX_RSR(DHCP_SOCKET)) > 0) - { - len = WIZCHIP_EXPORT(recvfrom)(DHCP_SOCKET, (uint8_t *)pDHCPMSG, len, svr_addr, &svr_port); - #ifdef _DHCP_DEBUG_ - printf("DHCP message : %d.%d.%d.%d(%d) %d received. \r\n",svr_addr[0],svr_addr[1],svr_addr[2], svr_addr[3],svr_port, len); - #endif - } - else return 0; - if (svr_port == DHCP_SERVER_PORT) { - // compare mac address - if ( (pDHCPMSG->chaddr[0] != DHCP_CHADDR[0]) || (pDHCPMSG->chaddr[1] != DHCP_CHADDR[1]) || - (pDHCPMSG->chaddr[2] != DHCP_CHADDR[2]) || (pDHCPMSG->chaddr[3] != DHCP_CHADDR[3]) || - (pDHCPMSG->chaddr[4] != DHCP_CHADDR[4]) || (pDHCPMSG->chaddr[5] != DHCP_CHADDR[5]) ) - return 0; - type = 0; - p = (uint8_t *)(&pDHCPMSG->op); - p = p + 240; // 240 = sizeof(RIP_MSG) + MAGIC_COOKIE size in RIP_MSG.opt - sizeof(RIP_MSG.opt) - e = p + (len - 240); - - while ( p < e ) { - - switch ( *p ) { - - case endOption : - p = e; // for break while(p < e) - break; - case padOption : - p++; - break; - case dhcpMessageType : - p++; - p++; - type = *p++; - break; - case subnetMask : - p++; - p++; - DHCP_allocated_sn[0] = *p++; - DHCP_allocated_sn[1] = *p++; - DHCP_allocated_sn[2] = *p++; - DHCP_allocated_sn[3] = *p++; - break; - case routersOnSubnet : - p++; - opt_len = *p++; - DHCP_allocated_gw[0] = *p++; - DHCP_allocated_gw[1] = *p++; - DHCP_allocated_gw[2] = *p++; - DHCP_allocated_gw[3] = *p++; - p = p + (opt_len - 4); - break; - case dns : - p++; - opt_len = *p++; - DHCP_allocated_dns[0] = *p++; - DHCP_allocated_dns[1] = *p++; - DHCP_allocated_dns[2] = *p++; - DHCP_allocated_dns[3] = *p++; - p = p + (opt_len - 4); - break; - case dhcpIPaddrLeaseTime : - p++; - opt_len = *p++; - dhcp_lease_time = *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - dhcp_lease_time = (dhcp_lease_time << 8) + *p++; - #ifdef _DHCP_DEBUG_ - dhcp_lease_time = 10; - #endif - break; - case dhcpServerIdentifier : - p++; - opt_len = *p++; - DHCP_SIP[0] = *p++; - DHCP_SIP[1] = *p++; - DHCP_SIP[2] = *p++; - DHCP_SIP[3] = *p++; - break; - default : - p++; - opt_len = *p++; - p += opt_len; - break; - } // switch - } // while - } // if - return type; -} - -uint8_t DHCP_run(void) -{ - uint8_t type; - uint8_t ret; - - if(dhcp_state == STATE_DHCP_STOP) return DHCP_STOPPED; - - if(getSn_SR(DHCP_SOCKET) != SOCK_UDP) - WIZCHIP_EXPORT(socket)(DHCP_SOCKET, Sn_MR_UDP, DHCP_CLIENT_PORT, 0x00); - - ret = DHCP_RUNNING; - type = parseDHCPMSG(); - - switch ( dhcp_state ) { - case STATE_DHCP_INIT : - DHCP_allocated_ip[0] = 0; - DHCP_allocated_ip[1] = 0; - DHCP_allocated_ip[2] = 0; - DHCP_allocated_ip[3] = 0; - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - case STATE_DHCP_DISCOVER : - if (type == DHCP_OFFER){ -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_OFFER\r\n"); -#endif - DHCP_allocated_ip[0] = pDHCPMSG->yiaddr[0]; - DHCP_allocated_ip[1] = pDHCPMSG->yiaddr[1]; - DHCP_allocated_ip[2] = pDHCPMSG->yiaddr[2]; - DHCP_allocated_ip[3] = pDHCPMSG->yiaddr[3]; - - send_DHCP_REQUEST(); - dhcp_state = STATE_DHCP_REQUEST; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_REQUEST : - if (type == DHCP_ACK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_ACK\r\n"); -#endif - if (check_DHCP_leasedIP()) { - // Network info assignment from DHCP - dhcp_ip_assign(); - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_LEASED; - } else { - // IP address conflict occurred - reset_DHCP_timeout(); - dhcp_ip_conflict(); - dhcp_state = STATE_DHCP_INIT; - } - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - - case STATE_DHCP_LEASED : - ret = DHCP_IP_LEASED; - if ((dhcp_lease_time != INFINITE_LEASETIME) && ((dhcp_lease_time/2) < dhcp_tick_1s)) { - -#ifdef _DHCP_DEBUG_ - printf("> Maintains the IP address \r\n"); -#endif - - type = 0; - OLD_allocated_ip[0] = DHCP_allocated_ip[0]; - OLD_allocated_ip[1] = DHCP_allocated_ip[1]; - OLD_allocated_ip[2] = DHCP_allocated_ip[2]; - OLD_allocated_ip[3] = DHCP_allocated_ip[3]; - - DHCP_XID++; - - send_DHCP_REQUEST(); - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_REREQUEST; - } - break; - - case STATE_DHCP_REREQUEST : - ret = DHCP_IP_LEASED; - if (type == DHCP_ACK) { - dhcp_retry_count = 0; - if (OLD_allocated_ip[0] != DHCP_allocated_ip[0] || - OLD_allocated_ip[1] != DHCP_allocated_ip[1] || - OLD_allocated_ip[2] != DHCP_allocated_ip[2] || - OLD_allocated_ip[3] != DHCP_allocated_ip[3]) - { - ret = DHCP_IP_CHANGED; - dhcp_ip_update(); - #ifdef _DHCP_DEBUG_ - printf(">IP changed.\r\n"); - #endif - - } - #ifdef _DHCP_DEBUG_ - else printf(">IP is continued.\r\n"); - #endif - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_LEASED; - } else if (type == DHCP_NAK) { - -#ifdef _DHCP_DEBUG_ - printf("> Receive DHCP_NACK, Failed to maintain ip\r\n"); -#endif - - reset_DHCP_timeout(); - - dhcp_state = STATE_DHCP_DISCOVER; - } else ret = check_DHCP_timeout(); - break; - default : - break; - } - - return ret; -} - -void DHCP_stop(void) -{ - WIZCHIP_EXPORT(close)(DHCP_SOCKET); - dhcp_state = STATE_DHCP_STOP; -} - -uint8_t check_DHCP_timeout(void) -{ - uint8_t ret = DHCP_RUNNING; - - if (dhcp_retry_count < MAX_DHCP_RETRY) { - if (dhcp_tick_next < dhcp_tick_1s) { - - switch ( dhcp_state ) { - case STATE_DHCP_DISCOVER : -// printf("<> state : STATE_DHCP_DISCOVER\r\n"); - send_DHCP_DISCOVER(); - break; - - case STATE_DHCP_REQUEST : -// printf("<> state : STATE_DHCP_REQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - case STATE_DHCP_REREQUEST : -// printf("<> state : STATE_DHCP_REREQUEST\r\n"); - - send_DHCP_REQUEST(); - break; - - default : - break; - } - - dhcp_tick_1s = 0; - dhcp_tick_next = dhcp_tick_1s + DHCP_WAIT_TIME; - dhcp_retry_count++; - } - } else { // timeout occurred - - switch(dhcp_state) { - case STATE_DHCP_DISCOVER: - dhcp_state = STATE_DHCP_INIT; - ret = DHCP_FAILED; - break; - case STATE_DHCP_REQUEST: - case STATE_DHCP_REREQUEST: - send_DHCP_DISCOVER(); - dhcp_state = STATE_DHCP_DISCOVER; - break; - default : - break; - } - reset_DHCP_timeout(); - } - return ret; -} - -int8_t check_DHCP_leasedIP(void) -{ - uint8_t tmp; - int32_t ret; - - //WIZchip RCR value changed for ARP Timeout count control - tmp = getRCR(); - setRCR(0x03); - - // IP conflict detection : ARP request - ARP reply - // Broadcasting ARP Request for check the IP conflict using UDP sendto() function - ret = WIZCHIP_EXPORT(sendto)(DHCP_SOCKET, (uint8_t *)"CHECK_IP_CONFLICT", 17, DHCP_allocated_ip, 5000); - - // RCR value restore - setRCR(tmp); - - if(ret == SOCKERR_TIMEOUT) { - // UDP send Timeout occurred : allocated IP address is unique, DHCP Success - -#ifdef _DHCP_DEBUG_ - printf("\r\n> Check leased IP - OK\r\n"); -#endif - - return 1; - } else { - // Received ARP reply or etc : IP address conflict occur, DHCP Failed - send_DHCP_DECLINE(); - - ret = dhcp_tick_1s; - while((dhcp_tick_1s - ret) < 2) ; // wait for 1s over; wait to complete to send DECLINE message; - - return 0; - } -} - -void DHCP_init(uint8_t s, DHCP_INIT_BUFFER_TYPE* buf) -{ - uint8_t zeroip[4] = {0,0,0,0}; - getSHAR(DHCP_CHADDR); - if((DHCP_CHADDR[0] | DHCP_CHADDR[1] | DHCP_CHADDR[2] | DHCP_CHADDR[3] | DHCP_CHADDR[4] | DHCP_CHADDR[5]) == 0x00) - { - // assign temporary mac address, you should be set SHAR before call this function. - DHCP_CHADDR[0] = 0x00; - DHCP_CHADDR[1] = 0x08; - DHCP_CHADDR[2] = 0xdc; - DHCP_CHADDR[3] = 0x00; - DHCP_CHADDR[4] = 0x00; - DHCP_CHADDR[5] = 0x00; - setSHAR(DHCP_CHADDR); - } - - DHCP_SOCKET = s; // SOCK_DHCP - pDHCPMSG = (RIP_MSG*)buf; - DHCP_XID = 0x12345678; - - // WIZchip Netinfo Clear - setSIPR(zeroip); - setSIPR(zeroip); - setGAR(zeroip); - - reset_DHCP_timeout(); - dhcp_state = STATE_DHCP_INIT; -} - - -/* Rset the DHCP timeout count and retry count. */ -void reset_DHCP_timeout(void) -{ - dhcp_tick_1s = 0; - dhcp_tick_next = DHCP_WAIT_TIME; - dhcp_retry_count = 0; -} - -void DHCP_time_handler(void) -{ - dhcp_tick_1s++; -} - -void getIPfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_ip[0]; - ip[1] = DHCP_allocated_ip[1]; - ip[2] = DHCP_allocated_ip[2]; - ip[3] = DHCP_allocated_ip[3]; -} - -void getGWfromDHCP(uint8_t* ip) -{ - ip[0] =DHCP_allocated_gw[0]; - ip[1] =DHCP_allocated_gw[1]; - ip[2] =DHCP_allocated_gw[2]; - ip[3] =DHCP_allocated_gw[3]; -} - -void getSNfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_sn[0]; - ip[1] = DHCP_allocated_sn[1]; - ip[2] = DHCP_allocated_sn[2]; - ip[3] = DHCP_allocated_sn[3]; -} - -void getDNSfromDHCP(uint8_t* ip) -{ - ip[0] = DHCP_allocated_dns[0]; - ip[1] = DHCP_allocated_dns[1]; - ip[2] = DHCP_allocated_dns[2]; - ip[3] = DHCP_allocated_dns[3]; -} - -uint32_t getDHCPLeasetime(void) -{ - return dhcp_lease_time; -} diff --git a/drivers/wiznet5k/internet/dhcp/dhcp.h b/drivers/wiznet5k/internet/dhcp/dhcp.h deleted file mode 100644 index 618a91498bd6d..0000000000000 --- a/drivers/wiznet5k/internet/dhcp/dhcp.h +++ /dev/null @@ -1,152 +0,0 @@ -//***************************************************************************** -// -//! \file dhcp.h -//! \brief DHCP APIs Header file. -//! \details Processig DHCP protocol as DISCOVER, OFFER, REQUEST, ACK, NACK and DECLINE. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/11/18> 1st Release -//! <2012/12/20> V1.1.0 -//! 1. Move unreferenced DEFINE to dhcp.c -//! <2012/12/26> V1.1.1 -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** -#ifndef _DHCP_H_ -#define _DHCP_H_ - -/* - * @brief - * @details If you want to display debug & processing message, Define _DHCP_DEBUG_ - * @note If defined, it depends on - */ - -//#define _DHCP_DEBUG_ - -/* Retry to processing DHCP */ -#define MAX_DHCP_RETRY 2 ///< Maximum retry count -#define DHCP_WAIT_TIME 3 ///< Wait Time 3s (was 10s) - -/* UDP port numbers for DHCP */ -#define DHCP_SERVER_PORT 67 ///< DHCP server port number -#define DHCP_CLIENT_PORT 68 ///< DHCP client port number - -#define MAGIC_COOKIE 0x63825363 ///< Any number. You can be modified it any number - -#define DCHP_HOST_NAME "WIZnet\0" - -/* - * @brief return value of @ref DHCP_run() - */ -enum -{ - DHCP_FAILED = 0, ///< Processing Fail - DHCP_RUNNING, ///< Processing DHCP protocol - DHCP_IP_ASSIGN, ///< First Occupy IP from DHPC server (if cbfunc == null, act as default default_ip_assign) - DHCP_IP_CHANGED, ///< Change IP address by new IP address from DHCP (if cbfunc == null, act as default default_ip_update) - DHCP_IP_LEASED, ///< Stand by - DHCP_STOPPED ///< Stop processing DHCP protocol -}; - -#define DHCP_INIT_BUFFER_TYPE uint32_t -#define DHCP_INIT_BUFFER_SIZE (137) -/* - * @brief DHCP client initialization (outside of the main loop) - * @param s - socket number - * @param buf - buffer for processing DHCP message - */ -void DHCP_init(uint8_t s, DHCP_INIT_BUFFER_TYPE* buf); - -/* - * @brief DHCP 1s Tick Timer handler - * @note SHOULD BE register to your system 1s Tick timer handler - */ -void DHCP_time_handler(void); - -/* - * @brief Register call back function - * @param ip_assign - callback func when IP is assigned from DHCP server first - * @param ip_update - callback func when IP is changed - * @prarm ip_conflict - callback func when the assigned IP is conflict with others. - */ -void reg_dhcp_cbfunc(void(*ip_assign)(void), void(*ip_update)(void), void(*ip_conflict)(void)); - -/* - * @brief DHCP client in the main loop - * @return The value is as the follow \n - * @ref DHCP_FAILED \n - * @ref DHCP_RUNNING \n - * @ref DHCP_IP_ASSIGN \n - * @ref DHCP_IP_CHANGED \n - * @ref DHCP_IP_LEASED \n - * @ref DHCP_STOPPED \n - * - * @note This function is always called by you main task. - */ -uint8_t DHCP_run(void); - -/* - * @brief Stop DHCP processing - * @note If you want to restart. call DHCP_init() and DHCP_run() - */ -void DHCP_stop(void); - -/* Get Network information assigned from DHCP server */ -/* - * @brief Get IP address - * @param ip - IP address to be returned - */ -void getIPfromDHCP(uint8_t* ip); -/* - * @brief Get Gateway address - * @param ip - Gateway address to be returned - */ -void getGWfromDHCP(uint8_t* ip); -/* - * @brief Get Subnet mask value - * @param ip - Subnet mask to be returned - */ -void getSNfromDHCP(uint8_t* ip); -/* - * @brief Get DNS address - * @param ip - DNS address to be returned - */ -void getDNSfromDHCP(uint8_t* ip); - -/* - * @brief Get the leased time by DHCP sever - * @return unit 1s - */ -uint32_t getDHCPLeasetime(void); - -#endif /* _DHCP_H_ */ diff --git a/drivers/wiznet5k/internet/dns/dns.c b/drivers/wiznet5k/internet/dns/dns.c deleted file mode 100644 index aa3a7380919b0..0000000000000 --- a/drivers/wiznet5k/internet/dns/dns.c +++ /dev/null @@ -1,572 +0,0 @@ -//***************************************************************************** -// -//! \file dns.c -//! \brief DNS APIs Implement file. -//! \details Send DNS query & Receive DNS reponse. \n -//! It depends on stdlib.h & string.h in ansi-c library -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Remove the unused define -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! <2018/10/04> Modified HAL_GetTick for use with CircuitPython by Nick Moore -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#include -#include -#include "supervisor/shared/tick.h" - -//#include "Ethernet/socket.h" -//#include "Internet/DNS/dns.h" -#include "../../ethernet/socket.h" -#include "dns.h" - -#ifdef _DNS_DEBUG_ - #include -#endif - -#define INITRTT 2000L /* Initial smoothed response time */ -#define MAXCNAME (MAX_DOMAIN_NAME + (MAX_DOMAIN_NAME>>1)) /* Maximum amount of cname recursion */ - -#define TYPE_A 1 /* Host address */ -#define TYPE_NS 2 /* Name server */ -#define TYPE_MD 3 /* Mail destination (obsolete) */ -#define TYPE_MF 4 /* Mail forwarder (obsolete) */ -#define TYPE_CNAME 5 /* Canonical name */ -#define TYPE_SOA 6 /* Start of Authority */ -#define TYPE_MB 7 /* Mailbox name (experimental) */ -#define TYPE_MG 8 /* Mail group member (experimental) */ -#define TYPE_MR 9 /* Mail rename name (experimental) */ -#define TYPE_NULL 10 /* Null (experimental) */ -#define TYPE_WKS 11 /* Well-known sockets */ -#define TYPE_PTR 12 /* Pointer record */ -#define TYPE_HINFO 13 /* Host information */ -#define TYPE_MINFO 14 /* Mailbox information (experimental)*/ -#define TYPE_MX 15 /* Mail exchanger */ -#define TYPE_TXT 16 /* Text strings */ -#define TYPE_ANY 255 /* Matches any type */ - -#define CLASS_IN 1 /* The ARPA Internet */ - -/* Round trip timing parameters */ -#define AGAIN 8 /* Average RTT gain = 1/8 */ -#define LAGAIN 3 /* Log2(AGAIN) */ -#define DGAIN 4 /* Mean deviation gain = 1/4 */ -#define LDGAIN 2 /* log2(DGAIN) */ - -/* Header for all domain messages */ -struct dhdr -{ - uint16_t id; /* Identification */ - uint8_t qr; /* Query/Response */ -#define QUERY 0 -#define RESPONSE 1 - uint8_t opcode; -#define IQUERY 1 - uint8_t aa; /* Authoratative answer */ - uint8_t tc; /* Truncation */ - uint8_t rd; /* Recursion desired */ - uint8_t ra; /* Recursion available */ - uint8_t rcode; /* Response code */ -#define NO_ERROR 0 -#define FORMAT_ERROR 1 -#define SERVER_FAIL 2 -#define NAME_ERROR 3 -#define NOT_IMPL 4 -#define REFUSED 5 - uint16_t qdcount; /* Question count */ - uint16_t ancount; /* Answer count */ - uint16_t nscount; /* Authority (name server) count */ - uint16_t arcount; /* Additional record count */ -}; - - -uint8_t* pDNSMSG; // DNS message buffer -uint8_t DNS_SOCKET; // SOCKET number for DNS -uint16_t DNS_MSGID; // DNS message ID - - -uint32_t HAL_GetTick(void) { - return supervisor_ticks_ms32(); -} - -uint32_t hal_sys_tick; - -/* converts uint16_t from network buffer to a host byte order integer. */ -uint16_t get16(uint8_t * s) -{ - uint16_t i; - i = *s++ << 8; - i = i + *s; - return i; -} - -/* copies uint16_t to the network buffer with network byte order. */ -uint8_t * put16(uint8_t * s, uint16_t i) -{ - *s++ = i >> 8; - *s++ = i; - return s; -} - - -/* - * CONVERT A DOMAIN NAME TO THE HUMAN-READABLE FORM - * - * Description : This function converts a compressed domain name to the human-readable form - * Arguments : msg - is a pointer to the reply message - * compressed - is a pointer to the domain name in reply message. - * buf - is a pointer to the buffer for the human-readable form name. - * len - is the MAX. size of buffer. - * Returns : the length of compressed message - */ -int parse_name(uint8_t * msg, uint8_t * compressed, char * buf, int16_t len) -{ - uint16_t slen; /* Length of current segment */ - uint8_t * cp; - int clen = 0; /* Total length of compressed name */ - int indirect = 0; /* Set if indirection encountered */ - int nseg = 0; /* Total number of segments in name */ - - cp = compressed; - - for (;;) - { - slen = *cp++; /* Length of this segment */ - - if (!indirect) clen++; - - if ((slen & 0xc0) == 0xc0) - { - if (!indirect) - clen++; - indirect = 1; - /* Follow indirection */ - cp = &msg[((slen & 0x3f)<<8) + *cp]; - slen = *cp++; - } - - if (slen == 0) /* zero length == all done */ - break; - - len -= slen + 1; - - if (len < 0) return -1; - - if (!indirect) clen += slen; - - while (slen-- != 0) *buf++ = (char)*cp++; - *buf++ = '.'; - nseg++; - } - - if (nseg == 0) - { - /* Root name; represent as single dot */ - *buf++ = '.'; - len--; - } - - *buf++ = '\0'; - len--; - - return clen; /* Length of compressed message */ -} - -/* - * PARSE QUESTION SECTION - * - * Description : This function parses the question record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the question record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_question(uint8_t * msg, uint8_t * cp) -{ - int len; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - - if (len == -1) return 0; - - cp += len; - cp += 2; /* type */ - cp += 2; /* class */ - - return cp; -} - - -/* - * PARSE ANSER SECTION - * - * Description : This function parses the answer record of the reply message. - * Arguments : msg - is a pointer to the reply message - * cp - is a pointer to the answer record. - * Returns : a pointer the to next record. - */ -uint8_t * dns_answer(uint8_t * msg, uint8_t * cp, uint8_t * ip_from_dns) -{ - int len, type; - char name[MAXCNAME]; - - len = parse_name(msg, cp, name, MAXCNAME); - - if (len == -1) return 0; - - cp += len; - type = get16(cp); - cp += 2; /* type */ - cp += 2; /* class */ - cp += 4; /* ttl */ - cp += 2; /* len */ - - - switch (type) - { - case TYPE_A: - /* Just read the address directly into the structure */ - ip_from_dns[0] = *cp++; - ip_from_dns[1] = *cp++; - ip_from_dns[2] = *cp++; - ip_from_dns[3] = *cp++; - break; - case TYPE_CNAME: - case TYPE_MB: - case TYPE_MG: - case TYPE_MR: - case TYPE_NS: - case TYPE_PTR: - /* These types all consist of a single domain name */ - /* convert it to ASCII format */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_HINFO: - len = *cp++; - cp += len; - - len = *cp++; - cp += len; - break; - case TYPE_MX: - cp += 2; - /* Get domain name of exchanger */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - break; - case TYPE_SOA: - /* Get domain name of name server */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - /* Get domain name of responsible person */ - len = parse_name(msg, cp, name, MAXCNAME); - if (len == -1) return 0; - - cp += len; - - cp += 4; - cp += 4; - cp += 4; - cp += 4; - cp += 4; - break; - case TYPE_TXT: - /* Just stash */ - break; - default: - /* Ignore */ - break; - } - - return cp; -} - -/* - * PARSE THE DNS REPLY - * - * Description : This function parses the reply message from DNS server. - * Arguments : dhdr - is a pointer to the header for DNS message - * buf - is a pointer to the reply message. - * len - is the size of reply message. - * Returns : -1 - Domain name length is too big - * 0 - Fail (Timeout or parse error) - * 1 - Success, - */ -int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns) -{ - uint16_t tmp; - uint16_t i; - uint8_t * msg; - uint8_t * cp; - - msg = pbuf; - memset(pdhdr, 0, sizeof(*pdhdr)); - - pdhdr->id = get16(&msg[0]); - tmp = get16(&msg[2]); - if (tmp & 0x8000) pdhdr->qr = 1; - - pdhdr->opcode = (tmp >> 11) & 0xf; - - if (tmp & 0x0400) pdhdr->aa = 1; - if (tmp & 0x0200) pdhdr->tc = 1; - if (tmp & 0x0100) pdhdr->rd = 1; - if (tmp & 0x0080) pdhdr->ra = 1; - - pdhdr->rcode = tmp & 0xf; - pdhdr->qdcount = get16(&msg[4]); - pdhdr->ancount = get16(&msg[6]); - pdhdr->nscount = get16(&msg[8]); - pdhdr->arcount = get16(&msg[10]); - - - /* Now parse the variable length sections */ - cp = &msg[12]; - - /* Question section */ - for (i = 0; i < pdhdr->qdcount; i++) - { - cp = dns_question(msg, cp); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - } - - /* Answer section */ - for (i = 0; i < pdhdr->ancount; i++) - { - cp = dns_answer(msg, cp, ip_from_dns); - if(!cp) - { -#ifdef _DNS_DEBUG_ - printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n"); -#endif - return -1; - } - - } - - /* Name server (authority) section */ - for (i = 0; i < pdhdr->nscount; i++) - { - ; - } - - /* Additional section */ - for (i = 0; i < pdhdr->arcount; i++) - { - ; - } - - if(pdhdr->rcode == 0) return 1; // No error - else return 0; -} - - -/* - * MAKE DNS QUERY MESSAGE - * - * Description : This function makes DNS query message. - * Arguments : op - Recursion desired - * name - is a pointer to the domain name. - * buf - is a pointer to the buffer for DNS message. - * len - is the MAX. size of buffer. - * Returns : the pointer to the DNS message. - */ -int16_t dns_makequery(uint16_t op, char * name, uint8_t * buf, uint16_t len) -{ - uint8_t *cp; - char *cp1; - char sname[MAXCNAME]; - char *dname; - uint16_t p; - uint16_t dlen; - - cp = buf; - - DNS_MSGID++; - cp = put16(cp, DNS_MSGID); - p = (op << 11) | 0x0100; /* Recursion desired */ - cp = put16(cp, p); - cp = put16(cp, 1); - cp = put16(cp, 0); - cp = put16(cp, 0); - cp = put16(cp, 0); - - strcpy(sname, name); - dname = sname; - dlen = strlen(dname); - for (;;) - { - /* Look for next dot */ - cp1 = strchr(dname, '.'); - - if (cp1 != NULL) len = cp1 - dname; /* More to come */ - else len = dlen; /* Last component */ - - *cp++ = len; /* Write length of component */ - if (len == 0) break; - - /* Copy component up to (but not including) dot */ - memcpy(cp, dname, len); - cp += len; - if (cp1 == NULL) - { - *cp++ = 0; /* Last one; write null and finish */ - break; - } - dname += len+1; - dlen -= len+1; - } - - cp = put16(cp, 0x0001); /* type */ - cp = put16(cp, 0x0001); /* class */ - - return ((int16_t)((uint32_t)(cp) - (uint32_t)(buf))); -} - -/* - * CHECK DNS TIMEOUT - * - * Description : This function check the DNS timeout - * Arguments : None. - * Returns : -1 - timeout occurred, 0 - timer over, but no timeout, 1 - no timer over, no timeout occur - * Note : timeout : retry count and timer both over. - */ - -int8_t check_DNS_timeout(void) -{ - static uint8_t retry_count; - - uint32_t tick = HAL_GetTick(); - if(tick - hal_sys_tick >= DNS_WAIT_TIME * 1000) - { - hal_sys_tick = tick; - if(retry_count >= MAX_DNS_RETRY) { - retry_count = 0; - return -1; // timeout occurred - } - retry_count++; - return 0; // timer over, but no timeout - } - - return 1; // no timer over, no timeout occur -} - - - -/* DNS CLIENT INIT */ -void DNS_init(uint8_t s, uint8_t * buf) -{ - DNS_SOCKET = s; // SOCK_DNS - pDNSMSG = buf; // User's shared buffer - DNS_MSGID = DNS_MSG_ID; -} - -/* DNS CLIENT RUN */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns) -{ - int8_t ret; - struct dhdr dhp; - uint8_t ip[4]; - uint16_t len, port; - int8_t ret_check_timeout; - - hal_sys_tick = HAL_GetTick(); - - // Socket open - WIZCHIP_EXPORT(socket)(DNS_SOCKET, Sn_MR_UDP, 0, 0); - -#ifdef _DNS_DEBUG_ - printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - - len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE); - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - - while (1) - { - if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0) - { - if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE; - len = WIZCHIP_EXPORT(recvfrom)(DNS_SOCKET, pDNSMSG, len, ip, &port); - #ifdef _DNS_DEBUG_ - printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len); - #endif - ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns); - break; - } - // Check Timeout - ret_check_timeout = check_DNS_timeout(); - if (ret_check_timeout < 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]); -#endif - return 0; // timeout occurred - } - else if (ret_check_timeout == 0) { - -#ifdef _DNS_DEBUG_ - printf("> DNS Timeout\r\n"); -#endif - WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN); - } - } - WIZCHIP_EXPORT(close)(DNS_SOCKET); - // Return value - // 0 > : failed / 1 - success - return ret; -} diff --git a/drivers/wiznet5k/internet/dns/dns.h b/drivers/wiznet5k/internet/dns/dns.h deleted file mode 100644 index 574b632a6a91b..0000000000000 --- a/drivers/wiznet5k/internet/dns/dns.h +++ /dev/null @@ -1,96 +0,0 @@ -//***************************************************************************** -// -//! \file dns.h -//! \brief DNS APIs Header file. -//! \details Send DNS query & Receive DNS reponse. -//! \version 1.1.0 -//! \date 2013/11/18 -//! \par Revision history -//! <2013/10/21> 1st Release -//! <2013/12/20> V1.1.0 -//! 1. Remove secondary DNS server in DNS_run -//! If 1st DNS_run failed, call DNS_run with 2nd DNS again -//! 2. DNS_timerHandler -> DNS_time_handler -//! 3. Move the no reference define to dns.c -//! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c -//! <2013/12/20> V1.1.0 -//! -//! \author Eric Jung & MidnightCow -//! \copyright -//! -//! Copyright (c) 2013, WIZnet Co., LTD. -//! All rights reserved. -//! -//! Redistribution and use in source and binary forms, with or without -//! modification, are permitted provided that the following conditions -//! are met: -//! -//! * Redistributions of source code must retain the above copyright -//! notice, this list of conditions and the following disclaimer. -//! * Redistributions in binary form must reproduce the above copyright -//! notice, this list of conditions and the following disclaimer in the -//! documentation and/or other materials provided with the distribution. -//! * Neither the name of the nor the names of its -//! contributors may be used to endorse or promote products derived -//! from this software without specific prior written permission. -//! -//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -//! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -//! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -//! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -//! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -//! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -//! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -//! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -//! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -//! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -//! THE POSSIBILITY OF SUCH DAMAGE. -// -//***************************************************************************** - -#ifndef _DNS_H_ -#define _DNS_H_ - -#include -/* - * @brief Define it for Debug & Monitor DNS processing. - * @note If defined, it depends on - */ - -//#define _DNS_DEBUG_ - -#define MAX_DNS_BUF_SIZE 256 ///< maximum size of DNS buffer. */ -/* - * @brief Maximum length of your queried Domain name - * @todo SHOULD BE defined it equal as or greater than your Domain name length + null character(1) - * @note SHOULD BE careful to stack overflow because it is allocated 1.5 times as MAX_DOMAIN_NAME in stack. - */ -#define MAX_DOMAIN_NAME 32 // for example "www.google.com" - -#define MAX_DNS_RETRY 2 ///< Requery Count -#define DNS_WAIT_TIME 4 ///< Wait response time. unit 1s. - -#define IPPORT_DOMAIN 53 ///< DNS server port number - -#define DNS_MSG_ID 0x1122 ///< ID for DNS message. You can be modified it any number -/* - * @brief DNS process initialize - * @param s : Socket number for DNS - * @param buf : Buffer for DNS message - */ -void DNS_init(uint8_t s, uint8_t * buf); - -/* - * @brief DNS process - * @details Send DNS query and receive DNS response - * @param dns_ip : DNS server ip address - * @param name : Domain name to be queried - * @param ip_from_dns : IP address from DNS server - * @return -1 : failed. @ref MAX_DOMIN_NAME is too small \n - * 0 : failed (Timeout or Parse error)\n - * 1 : success - * @note This function blocks until success or fail. max time = @ref MAX_DNS_RETRY * @ref DNS_WAIT_TIME - */ -int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns); - -#endif /* _DNS_H_ */ diff --git a/extmod/axtls-include/config.h b/extmod/axtls-include/config.h new file mode 100644 index 0000000000000..4cb1aed9ca71c --- /dev/null +++ b/extmod/axtls-include/config.h @@ -0,0 +1,117 @@ +/* + * Automatically generated header file: don't edit + */ + +#define HAVE_DOT_CONFIG 1 +#define CONFIG_PLATFORM_LINUX 1 +#undef CONFIG_PLATFORM_CYGWIN +#undef CONFIG_PLATFORM_WIN32 + +/* + * General Configuration + */ +#define PREFIX "/usr/local" +#undef CONFIG_DEBUG +#undef CONFIG_STRIP_UNWANTED_SECTIONS +#undef CONFIG_VISUAL_STUDIO_7_0 +#undef CONFIG_VISUAL_STUDIO_8_0 +#undef CONFIG_VISUAL_STUDIO_10_0 +#define CONFIG_VISUAL_STUDIO_7_0_BASE "" +#define CONFIG_VISUAL_STUDIO_8_0_BASE "" +#define CONFIG_VISUAL_STUDIO_10_0_BASE "" +#define CONFIG_EXTRA_CFLAGS_OPTIONS "" +#define CONFIG_EXTRA_LDFLAGS_OPTIONS "" + +/* + * SSL Library + */ +#undef CONFIG_SSL_SERVER_ONLY +#undef CONFIG_SSL_CERT_VERIFICATION +#undef CONFIG_SSL_FULL_MODE +#define CONFIG_SSL_SKELETON_MODE 1 +#define CONFIG_SSL_ENABLE_SERVER 1 +#define CONFIG_SSL_ENABLE_CLIENT 1 +#undef CONFIG_SSL_DIAGNOSTICS +#define CONFIG_SSL_PROT_LOW 1 +#undef CONFIG_SSL_PROT_MEDIUM +#undef CONFIG_SSL_PROT_HIGH +#define CONFIG_SSL_AES 1 +#define CONFIG_SSL_USE_DEFAULT_KEY 1 +#define CONFIG_SSL_PRIVATE_KEY_LOCATION "" +#define CONFIG_SSL_PRIVATE_KEY_PASSWORD "" +#define CONFIG_SSL_X509_CERT_LOCATION "" +#undef CONFIG_SSL_GENERATE_X509_CERT +#define CONFIG_SSL_X509_COMMON_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME "" +#undef CONFIG_SSL_HAS_PEM +#undef CONFIG_SSL_USE_PKCS12 +#define CONFIG_SSL_EXPIRY_TIME +#define CONFIG_X509_MAX_CA_CERTS 0 +#define CONFIG_SSL_MAX_CERTS 3 +#undef CONFIG_SSL_CTX_MUTEXING +#undef CONFIG_USE_DEV_URANDOM +#undef CONFIG_WIN32_USE_CRYPTO_LIB +#undef CONFIG_OPENSSL_COMPATIBLE +#undef CONFIG_PERFORMANCE_TESTING +#undef CONFIG_SSL_TEST +#undef CONFIG_AXTLSWRAP +#undef CONFIG_AXHTTPD +#undef CONFIG_HTTP_STATIC_BUILD +#define CONFIG_HTTP_PORT +#define CONFIG_HTTP_HTTPS_PORT +#define CONFIG_HTTP_SESSION_CACHE_SIZE +#define CONFIG_HTTP_WEBROOT "" +#define CONFIG_HTTP_TIMEOUT +#undef CONFIG_HTTP_HAS_CGI +#define CONFIG_HTTP_CGI_EXTENSIONS "" +#undef CONFIG_HTTP_ENABLE_LUA +#define CONFIG_HTTP_LUA_PREFIX "" +#undef CONFIG_HTTP_BUILD_LUA +#define CONFIG_HTTP_CGI_LAUNCHER "" +#undef CONFIG_HTTP_DIRECTORIES +#undef CONFIG_HTTP_HAS_AUTHORIZATION +#undef CONFIG_HTTP_HAS_IPV6 +#undef CONFIG_HTTP_ENABLE_DIFFERENT_USER +#define CONFIG_HTTP_USER "" +#undef CONFIG_HTTP_VERBOSE +#undef CONFIG_HTTP_IS_DAEMON + +/* + * Language Bindings + */ +#undef CONFIG_BINDINGS +#undef CONFIG_CSHARP_BINDINGS +#undef CONFIG_VBNET_BINDINGS +#define CONFIG_DOT_NET_FRAMEWORK_BASE "" +#undef CONFIG_JAVA_BINDINGS +#define CONFIG_JAVA_HOME "" +#undef CONFIG_PERL_BINDINGS +#define CONFIG_PERL_CORE "" +#define CONFIG_PERL_LIB "" +#undef CONFIG_LUA_BINDINGS +#define CONFIG_LUA_CORE "" + +/* + * Samples + */ +#undef CONFIG_SAMPLES +#undef CONFIG_C_SAMPLES +#undef CONFIG_CSHARP_SAMPLES +#undef CONFIG_VBNET_SAMPLES +#undef CONFIG_JAVA_SAMPLES +#undef CONFIG_PERL_SAMPLES +#undef CONFIG_LUA_SAMPLES +#undef CONFIG_BIGINT_CLASSICAL +#undef CONFIG_BIGINT_MONTGOMERY +#undef CONFIG_BIGINT_BARRETT +#undef CONFIG_BIGINT_CRT +#undef CONFIG_BIGINT_KARATSUBA +#define MUL_KARATSUBA_THRESH +#define SQU_KARATSUBA_THRESH +#undef CONFIG_BIGINT_SLIDING_WINDOW +#undef CONFIG_BIGINT_SQUARE +#undef CONFIG_BIGINT_CHECK_ON +#undef CONFIG_INTEGER_32BIT +#undef CONFIG_INTEGER_16BIT +#undef CONFIG_INTEGER_8BIT diff --git a/extmod/axtls-include/version.h b/extmod/axtls-include/version.h new file mode 100644 index 0000000000000..df2260e4c6817 --- /dev/null +++ b/extmod/axtls-include/version.h @@ -0,0 +1 @@ +#define AXTLS_VERSION "(no version)" diff --git a/extmod/crypto-algorithms/sha256.c b/extmod/crypto-algorithms/sha256.c index 276611cfd5032..9b5e45d23df70 100644 --- a/extmod/crypto-algorithms/sha256.c +++ b/extmod/crypto-algorithms/sha256.c @@ -14,6 +14,7 @@ /*************************** HEADER FILES ***************************/ #include +#include #include "sha256.h" /****************************** MACROS ******************************/ diff --git a/extmod/machine_mem.c b/extmod/machine_mem.c deleted file mode 100644 index 8944c3a6665d1..0000000000000 --- a/extmod/machine_mem.c +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" -#include "extmod/machine_mem.h" - -#if MICROPY_PY_MACHINE - -// If you wish to override the functions for mapping the machine_mem read/write -// address, then add a #define for MICROPY_MACHINE_MEM_GET_READ_ADDR and/or -// MICROPY_MACHINE_MEM_GET_WRITE_ADDR in your mpconfigport.h. Since the -// prototypes are identical, it is allowable for both of the macros to evaluate -// the to same function. -// -// It is expected that the modmachine.c file for a given port will provide the -// implementations, if the default implementation isn't used. - -#if !defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) || !defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -STATIC uintptr_t machine_mem_get_addr(mp_obj_t addr_o, uint align) { - uintptr_t addr = mp_obj_int_get_truncated(addr_o); - if ((addr & (align - 1)) != 0) { - mp_raise_ValueError_varg(translate("address %08x is not aligned to %d bytes"), addr, align); - } - return addr; -} -#if !defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) -#define MICROPY_MACHINE_MEM_GET_READ_ADDR machine_mem_get_addr -#endif -#if !defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -#define MICROPY_MACHINE_MEM_GET_WRITE_ADDR machine_mem_get_addr -#endif -#endif - -STATIC void machine_mem_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - (void)kind; - machine_mem_obj_t *self = MP_OBJ_TO_PTR(self_in); - mp_printf(print, "<%u-bit memory>", 8 * self->elem_size); -} - -STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - // TODO support slice index to read/write multiple values at once - machine_mem_obj_t *self = MP_OBJ_TO_PTR(self_in); - if (value == MP_OBJ_NULL) { - // delete - return MP_OBJ_NULL; // op not supported - } else if (value == MP_OBJ_SENTINEL) { - // load - 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; - } - return mp_obj_new_int(val); - } else { - // store - 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; - } - return mp_const_none; - } -} - -const mp_obj_type_t machine_mem_type = { - { &mp_type_type }, - .name = MP_QSTR_mem, - .print = machine_mem_print, - .subscr = machine_mem_subscr, -}; - -const machine_mem_obj_t machine_mem8_obj = {{&machine_mem_type}, 1}; -const machine_mem_obj_t machine_mem16_obj = {{&machine_mem_type}, 2}; -const machine_mem_obj_t machine_mem32_obj = {{&machine_mem_type}, 4}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_mem.h b/extmod/machine_mem.h deleted file mode 100644 index 735887c60e5a1..0000000000000 --- a/extmod/machine_mem.h +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2015 Damien P. George -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H - -#include "py/obj.h" - -typedef struct _machine_mem_obj_t { - mp_obj_base_t base; - unsigned elem_size; // in bytes -} machine_mem_obj_t; - -extern const mp_obj_type_t machine_mem_type; - -extern const machine_mem_obj_t machine_mem8_obj; -extern const machine_mem_obj_t machine_mem16_obj; -extern const machine_mem_obj_t machine_mem32_obj; - -#if defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) -uintptr_t MICROPY_MACHINE_MEM_GET_READ_ADDR(mp_obj_t addr_o, uint align); -#endif -#if defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) -uintptr_t MICROPY_MACHINE_MEM_GET_WRITE_ADDR(mp_obj_t addr_o, uint align); -#endif - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H diff --git a/extmod/machine_pinbase.c b/extmod/machine_pinbase.c deleted file mode 100644 index a5e33c560213b..0000000000000 --- a/extmod/machine_pinbase.c +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2016 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#include "py/mpconfig.h" -#if MICROPY_PY_MACHINE - -#include "py/obj.h" -#include "py/runtime.h" -#include "extmod/virtpin.h" -#include "extmod/machine_pinbase.h" - -// PinBase class - -// As this is abstract class, its instance is null. -// But there should be an instance, as the rest of instance code -// expects that there will be concrete object for inheritance. -typedef struct _mp_pinbase_t { - mp_obj_base_t base; -} mp_pinbase_t; - -STATIC const mp_pinbase_t pinbase_singleton = { - .base = { &machine_pinbase_type }, -}; - -STATIC mp_obj_t pinbase_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - (void)type; - (void)n_args; - (void)args; - (void)kw_args; - return MP_OBJ_FROM_PTR(&pinbase_singleton); -} - -mp_uint_t pinbase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); -mp_uint_t pinbase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) { - (void)errcode; - switch (request) { - case MP_PIN_READ: { - mp_obj_t dest[2]; - mp_load_method(obj, MP_QSTR_value, dest); - return mp_obj_get_int(mp_call_method_n_kw(0, 0, dest)); - } - case MP_PIN_WRITE: { - mp_obj_t dest[3]; - mp_load_method(obj, MP_QSTR_value, dest); - dest[2] = (arg == 0 ? mp_const_false : mp_const_true); - mp_call_method_n_kw(1, 0, dest); - return 0; - } - } - return -1; -} - -STATIC const mp_pin_p_t pinbase_pin_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_pin) - .ioctl = pinbase_ioctl, -}; - -const mp_obj_type_t machine_pinbase_type = { - { &mp_type_type }, - .name = MP_QSTR_PinBase, - .make_new = pinbase_make_new, - .protocol = &pinbase_pin_p, -}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_pinbase.h b/extmod/machine_pinbase.h deleted file mode 100644 index b747563a1e726..0000000000000 --- a/extmod/machine_pinbase.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2016 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H - -#include "py/obj.h" - -extern const mp_obj_type_t machine_pinbase_type; - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H diff --git a/extmod/machine_pulse.c b/extmod/machine_pulse.c deleted file mode 100644 index eaee12b36720b..0000000000000 --- a/extmod/machine_pulse.c +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" -#include "py/mperrno.h" -#include "extmod/machine_pulse.h" - -#if MICROPY_PY_MACHINE_PULSE - -mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us) { - mp_uint_t start = mp_hal_ticks_us(); - while (mp_hal_pin_read(pin) != pulse_level) { - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { - return (mp_uint_t)-2; - } - } - start = mp_hal_ticks_us(); - while (mp_hal_pin_read(pin) == pulse_level) { - if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { - return (mp_uint_t)-1; - } - } - return mp_hal_ticks_us() - start; -} - -STATIC mp_obj_t machine_time_pulse_us_(size_t n_args, const mp_obj_t *args) { - mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(args[0]); - int level = 0; - if (mp_obj_is_true(args[1])) { - level = 1; - } - mp_uint_t timeout_us = 1000000; - if (n_args > 2) { - timeout_us = mp_obj_get_int(args[2]); - } - mp_uint_t us = machine_time_pulse_us(pin, level, timeout_us); - // May return -1 or -2 in case of timeout - return mp_obj_new_int(us); -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj, 2, 3, machine_time_pulse_us_); - -#endif diff --git a/extmod/machine_pulse.h b/extmod/machine_pulse.h deleted file mode 100644 index a9b0ebc1b4910..0000000000000 --- a/extmod/machine_pulse.h +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H - -#include "py/obj.h" -#include "py/mphal.h" - -mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us); - -MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj); - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H diff --git a/extmod/machine_signal.c b/extmod/machine_signal.c deleted file mode 100644 index a215fc38898c1..0000000000000 --- a/extmod/machine_signal.c +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) 2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#include "py/mpconfig.h" -#if MICROPY_PY_MACHINE - -#include - -#include "py/obj.h" -#include "py/runtime.h" -#include "extmod/virtpin.h" -#include "extmod/machine_signal.h" - -// Signal class - -typedef struct _machine_signal_t { - mp_obj_base_t base; - mp_obj_t pin; - bool invert; -} machine_signal_t; - -STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - mp_obj_t pin = args[0]; - 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); - - if (pin_p == NULL) { - // If first argument isn't a Pin-like object, we filter out "invert" - // from keyword arguments and pass them all to the exported Pin - // constructor to create one. - mp_obj_t *pin_args = mp_local_alloc((n_args + n_kw * 2) * sizeof(mp_obj_t)); - memcpy(pin_args, args, n_args * sizeof(mp_obj_t)); - const mp_obj_t *src = args + n_args; - mp_obj_t *dst = pin_args + n_args; - mp_obj_t *sig_value = NULL; - for (size_t cnt = n_kw; cnt; cnt--) { - if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { - invert = mp_obj_is_true(src[1]); - n_kw--; - } else { - *dst++ = *src; - *dst++ = src[1]; - } - if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_value)) { - // Value is pertained to Signal, so we should invert - // it for Pin if needed, and we should do it only when - // inversion status is guaranteedly known. - sig_value = dst - 1; - } - src += 2; - } - - if (invert && sig_value != NULL) { - *sig_value = mp_obj_is_true(*sig_value) ? MP_OBJ_NEW_SMALL_INT(0) : MP_OBJ_NEW_SMALL_INT(1); - } - - // Here we pass NULL as a type, hoping that mp_pin_make_new() - // will just ignore it as set a concrete type. If not, we'd need - // to expose port's "default" pin type too. - pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args); - - mp_local_free(pin_args); - } - else - #endif - // Otherwise there should be 1 or 2 args - { - if (n_args == 1) { - if (kw_args == NULL || kw_args->used == 0) { - } else if (kw_args->used == 1 && kw_args->table[0].key == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { - invert = mp_obj_is_true(kw_args->table[0].value); - } else { - goto error; - } - } else { - error: - mp_raise_TypeError(NULL); - } - } - - machine_signal_t *o = m_new_obj(machine_signal_t); - o->base.type = type; - o->pin = pin; - o->invert = invert; - return MP_OBJ_FROM_PTR(o); -} - -STATIC mp_uint_t signal_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { - (void)errcode; - machine_signal_t *self = MP_OBJ_TO_PTR(self_in); - - switch (request) { - case MP_PIN_READ: { - return mp_virtual_pin_read(self->pin) ^ self->invert; - } - case MP_PIN_WRITE: { - mp_virtual_pin_write(self->pin, arg ^ self->invert); - return 0; - } - } - return -1; -} - -// fast method for getting/setting signal value -STATIC mp_obj_t signal_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num_kw_array(n_args, n_kw, 0, 1, false); - if (n_args == 0) { - // get pin - return MP_OBJ_NEW_SMALL_INT(mp_virtual_pin_read(self_in)); - } else { - // set pin - mp_virtual_pin_write(self_in, mp_obj_is_true(args[0])); - return mp_const_none; - } -} - -STATIC mp_obj_t signal_value(size_t n_args, const mp_obj_t *args) { - return signal_call(args[0], n_args - 1, 0, args + 1); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(signal_value_obj, 1, 2, signal_value); - -STATIC mp_obj_t signal_on(mp_obj_t self_in) { - mp_virtual_pin_write(self_in, 1); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_on_obj, signal_on); - -STATIC mp_obj_t signal_off(mp_obj_t self_in) { - mp_virtual_pin_write(self_in, 0); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_off_obj, signal_off); - -STATIC const mp_rom_map_elem_t signal_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&signal_value_obj) }, - { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&signal_on_obj) }, - { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&signal_off_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(signal_locals_dict, signal_locals_dict_table); - -STATIC const mp_pin_p_t signal_pin_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_pin) - .ioctl = signal_ioctl, -}; - -const mp_obj_type_t machine_signal_type = { - { &mp_type_type }, - .name = MP_QSTR_Signal, - .make_new = signal_make_new, - .call = signal_call, - .protocol = &signal_pin_p, - .locals_dict = (void*)&signal_locals_dict, -}; - -#endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_signal.h b/extmod/machine_signal.h deleted file mode 100644 index 17ffe5563f85e..0000000000000 --- a/extmod/machine_signal.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// -// SPDX-License-Identifier: MIT - -#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H -#define MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H - -#include "py/obj.h" - -extern const mp_obj_type_t machine_signal_type; - -#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H diff --git a/extmod/modbtree.c b/extmod/modbtree.c index 9f5261b1b74ec..96b60018fe6bb 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(MP_OBJ_TO_PTR(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 07a50a2f4cef9..ce280090f4656 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 deleted file mode 100644 index 20cc3a65949f2..0000000000000 --- a/extmod/modlwip.c +++ /dev/null @@ -1,1437 +0,0 @@ -// Copyright (c) 2015 Galen Hazelwood -// Copyright (c) 2015-2017 Paul Sokolovsky -// SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// -// SPDX-License-Identifier: MIT - -#include -#include - -#include "py/objlist.h" -#include "py/runtime.h" -#include "py/stream.h" -#include "py/mperrno.h" -#include "py/mphal.h" - -#include "lib/netutils/netutils.h" - -#include "lwip/init.h" -#include "lwip/tcp.h" -#include "lwip/udp.h" -//#include "lwip/raw.h" -#include "lwip/dns.h" -#include "lwip/igmp.h" -#if LWIP_VERSION_MAJOR < 2 -#include "lwip/timers.h" -#include "lwip/tcp_impl.h" -#else -#include "lwip/timeouts.h" -#include "lwip/priv/tcp_priv.h" -#endif - -#if 0 // print debugging info -#define DEBUG_printf DEBUG_printf -#else // don't print debugging info -#define DEBUG_printf(...) (void)0 -#endif - -// All socket options should be globally distinct, -// because we ignore option levels for efficiency. -#define IP_ADD_MEMBERSHIP 0x400 - -// For compatibilily with older lwIP versions. -#ifndef ip_set_option -#define ip_set_option(pcb, opt) ((pcb)->so_options |= (opt)) -#endif -#ifndef ip_reset_option -#define ip_reset_option(pcb, opt) ((pcb)->so_options &= ~(opt)) -#endif - -#if MICROPY_PY_LWIP_SLIP -#include "netif/slipif.h" -#include "lwip/sio.h" -#endif - -#if MICROPY_PY_LWIP_SLIP -/******************************************************************************/ -// Slip object for modlwip. Requires a serial driver for the port that supports -// the lwip serial callback functions. - -typedef struct _lwip_slip_obj_t { - mp_obj_base_t base; - struct netif lwip_netif; -} lwip_slip_obj_t; - -// Slip object is unique for now. Possibly can fix this later. FIXME -STATIC lwip_slip_obj_t lwip_slip_obj; - -// Declare these early. -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); -} - -STATIC const mp_obj_type_t lwip_slip_type; - -// lwIP SLIP callback functions -sio_fd_t sio_open(u8_t dvnum) { - // We support singleton SLIP interface, so just return any truish value. - return (sio_fd_t)1; -} - -void sio_send(u8_t c, sio_fd_t fd) { - mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); - int error; - type->stream_p->write(MP_STATE_VM(lwip_slip_stream), &c, 1, &error); -} - -u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len) { - mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); - int error; - mp_uint_t out_sz = type->stream_p->read(MP_STATE_VM(lwip_slip_stream), data, len, &error); - if (out_sz == MP_STREAM_ERROR) { - if (mp_is_nonblocking_error(error)) { - return 0; - } - // Can't do much else, can we? - return 0; - } - return out_sz; -} - -// constructor lwip.slip(device=integer, iplocal=string, ipremote=string) -STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num(n_args, n_kw, 3, 3, false); - - lwip_slip_obj.base.type = &lwip_slip_type; - - MP_STATE_VM(lwip_slip_stream) = args[0]; - - ip_addr_t iplocal, ipremote; - if (!ipaddr_aton(mp_obj_str_get_str(args[1]), &iplocal)) { - mp_raise_ValueError("not a valid local IP"); - } - if (!ipaddr_aton(mp_obj_str_get_str(args[2]), &ipremote)) { - mp_raise_ValueError("not a valid remote IP"); - } - - 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"); - } - netif_set_up(n); - netif_set_default(n); - mod_lwip_register_poll(slip_lwip_poll, n); - - return (mp_obj_t)&lwip_slip_obj; -} - -STATIC mp_obj_t lwip_slip_status(mp_obj_t self_in) { - // Null function for now. - return mp_const_none; -} - -STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_slip_status_obj, lwip_slip_status); - -STATIC const mp_rom_map_elem_t lwip_slip_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&lwip_slip_status_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(lwip_slip_locals_dict, lwip_slip_locals_dict_table); - -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, -}; - -#endif // MICROPY_PY_LWIP_SLIP - -/******************************************************************************/ -// Table to convert lwIP err_t codes to socket errno codes, from the lwIP -// socket API. - -// 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) - -// Extension to lwIP error codes -#define _ERR_BADF -16 -// TODO: We just know that change happened somewhere between 1.4.0 and 1.4.1, -// investigate in more detail. -#if LWIP_VERSION_MACRO < 0x01040100 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK. */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value. */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ - - MP_ECONNABORTED, /* ERR_ABRT -8 Connection aborted. */ - MP_ECONNRESET, /* ERR_RST -9 Connection reset. */ - MP_ENOTCONN, /* ERR_CLSD -10 Connection closed. */ - MP_ENOTCONN, /* ERR_CONN -11 Not connected. */ - MP_EIO, /* ERR_ARG -12 Illegal argument. */ - MP_EADDRINUSE, /* ERR_USE -13 Address in use. */ - -1, /* ERR_IF -14 Low-level netif error */ - MP_EALREADY, /* ERR_ISCONN -15 Already connected. */ - MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ -}; -#elif LWIP_VERSION_MACRO < 0x02000000 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK. */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value. */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ - - MP_EADDRINUSE, /* ERR_USE -8 Address in use. */ - MP_EALREADY, /* ERR_ISCONN -9 Already connected. */ - MP_ECONNABORTED, /* ERR_ABRT -10 Connection aborted. */ - MP_ECONNRESET, /* ERR_RST -11 Connection reset. */ - MP_ENOTCONN, /* ERR_CLSD -12 Connection closed. */ - MP_ENOTCONN, /* ERR_CONN -13 Not connected. */ - MP_EIO, /* ERR_ARG -14 Illegal argument. */ - -1, /* ERR_IF -15 Low-level netif error */ - MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ -}; -#else -// Matches lwIP 2.0.3 -#undef _ERR_BADF -#define _ERR_BADF -17 -static const int error_lookup_table[] = { - 0, /* ERR_OK 0 No error, everything OK */ - MP_ENOMEM, /* ERR_MEM -1 Out of memory error */ - MP_ENOBUFS, /* ERR_BUF -2 Buffer error */ - MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ - MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem */ - MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ - MP_EINVAL, /* ERR_VAL -6 Illegal value */ - MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block */ - MP_EADDRINUSE, /* ERR_USE -8 Address in use */ - MP_EALREADY, /* ERR_ALREADY -9 Already connecting */ - MP_EALREADY, /* ERR_ISCONN -10 Conn already established */ - MP_ENOTCONN, /* ERR_CONN -11 Not connected */ - -1, /* ERR_IF -12 Low-level netif error */ - MP_ECONNABORTED, /* ERR_ABRT -13 Connection aborted */ - MP_ECONNRESET, /* ERR_RST -14 Connection reset */ - MP_ENOTCONN, /* ERR_CLSD -15 Connection closed */ - MP_EIO, /* ERR_ARG -16 Illegal argument. */ - MP_EBADF, /* _ERR_BADF -17 Closed socket (null pcb) */ -}; -#endif - -/*******************************************************************************/ -// The socket object provided by lwip.socket. - -#define MOD_NETWORK_AF_INET (2) -#define MOD_NETWORK_AF_INET6 (10) - -#define MOD_NETWORK_SOCK_STREAM (1) -#define MOD_NETWORK_SOCK_DGRAM (2) -#define MOD_NETWORK_SOCK_RAW (3) - -typedef struct _lwip_socket_obj_t { - mp_obj_base_t base; - - volatile union { - struct tcp_pcb *tcp; - struct udp_pcb *udp; - } pcb; - volatile union { - struct pbuf *pbuf; - struct tcp_pcb *connection; - } incoming; - mp_obj_t callback; - byte peer[4]; - mp_uint_t peer_port; - mp_uint_t timeout; - uint16_t recv_offset; - - uint8_t domain; - uint8_t type; - - #define STATE_NEW 0 - #define STATE_CONNECTING 1 - #define STATE_CONNECTED 2 - #define STATE_PEER_CLOSED 3 - // Negative value is lwIP error - int8_t state; -} lwip_socket_obj_t; - -static inline void poll_sockets(void) { -#ifdef MICROPY_EVENT_POLL_HOOK - MICROPY_EVENT_POLL_HOOK; -#else - mp_hal_delay_ms(1); -#endif -} - -/*******************************************************************************/ -// Callback functions for the lwIP raw API. - -static inline void exec_user_callback(lwip_socket_obj_t *socket) { - if (socket->callback != MP_OBJ_NULL) { - mp_call_function_1_protected(socket->callback, socket); - } -} - -// Callback for incoming UDP packets. We simply stash the packet and the source address, -// in case we need it for recvfrom. -#if LWIP_VERSION_MAJOR < 2 -STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port) -#else -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; - - if (socket->incoming.pbuf != NULL) { - // That's why they call it "unreliable". No room in the inn, drop the packet. - pbuf_free(p); - } else { - socket->incoming.pbuf = p; - socket->peer_port = (mp_uint_t)port; - memcpy(&socket->peer, addr, sizeof(socket->peer)); - } -} - -// 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; - - // Pass the error code back via the connection variable. - socket->state = err; - // If we got here, the lwIP stack either has deallocated or will deallocate the pcb. - socket->pcb.tcp = NULL; -} - -// 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; - - socket->state = STATE_CONNECTED; - return ERR_OK; -} - -// By default, a child socket of listen socket is created with recv -// handler which discards incoming pbuf's. We don't want to do that, -// so set this handler which requests lwIP to keep pbuf's and deliver -// them later. We cannot cache pbufs in child socket on Python side, -// until it is created in accept(). -STATIC err_t _lwip_tcp_recv_unaccepted(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { - return ERR_BUF; -} - -// "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; - tcp_poll(pcb, NULL, 0); - exec_user_callback(socket); - return ERR_OK; -} - -// 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; - tcp_recv(newpcb, _lwip_tcp_recv_unaccepted); - - if (socket->incoming.connection != NULL) { - DEBUG_printf("_lwip_tcp_accept: Tried to queue >1 pcb waiting for accept\n"); - // We need to handle this better. This single-level structure makes the - // backlog setting kind of pointless. FIXME - return ERR_BUF; - } else { - socket->incoming.connection = newpcb; - if (socket->callback != MP_OBJ_NULL) { - // Schedule accept callback to be called when lwIP is done - // with processing this incoming connection on its side and - // is idle. - tcp_poll(newpcb, _lwip_tcp_accept_finished, 1); - } - return ERR_OK; - } -} - -// 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; - - if (p == NULL) { - // Other side has closed connection. - DEBUG_printf("_lwip_tcp_recv[%p]: other side closed connection\n", socket); - socket->state = STATE_PEER_CLOSED; - exec_user_callback(socket); - return ERR_OK; - } - - if (socket->incoming.pbuf == NULL) { - socket->incoming.pbuf = p; - } else { - #ifdef SOCKET_SINGLE_PBUF - return ERR_BUF; - #else - pbuf_cat(socket->incoming.pbuf, p); - #endif - } - - exec_user_callback(socket); - - return ERR_OK; -} - -/*******************************************************************************/ -// Functions for socket send/receive operations. Socket send/recv and friends call -// these to do the work. - -// Helper function for send/sendto to handle UDP packets. -STATIC mp_uint_t lwip_udp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) { - if (len > 0xffff) { - // Any packet that big is probably going to fail the pbuf_alloc anyway, but may as well try - len = 0xffff; - } - - // FIXME: maybe PBUF_ROM? - struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); - if (p == NULL) { - *_errno = MP_ENOMEM; - return -1; - } - - memcpy(p->payload, buf, len); - - err_t err; - if (ip == NULL) { - err = udp_send(socket->pcb.udp, p); - } else { - ip_addr_t dest; - IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); - err = udp_sendto(socket->pcb.udp, p, &dest, port); - } - - pbuf_free(p); - - // udp_sendto can return 1 on occasion for ESP8266 port. It's not known why - // but it seems that the send actually goes through without error in this case. - // So we treat such cases as a success until further investigation. - if (err != ERR_OK && err != 1) { - *_errno = error_lookup_table[-err]; - return -1; - } - - return len; -} - -// Helper function for recv/recvfrom to handle UDP packets -STATIC mp_uint_t lwip_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) { - - if (socket->incoming.pbuf == NULL) { - 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) { - *_errno = MP_ETIMEDOUT; - return -1; - } - } else { - while (socket->incoming.pbuf == NULL) { - poll_sockets(); - } - } - } - - if (ip != NULL) { - memcpy(ip, &socket->peer, sizeof(socket->peer)); - *port = socket->peer_port; - } - - struct pbuf *p = socket->incoming.pbuf; - - u16_t result = pbuf_copy_partial(p, buf, ((p->tot_len > len) ? len : p->tot_len), 0); - pbuf_free(p); - socket->incoming.pbuf = NULL; - - 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); - - -// Helper function for send/sendto to handle TCP packets -STATIC mp_uint_t lwip_tcp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) { - // Check for any pending errors - STREAM_ERROR_CHECK(socket); - - u16_t available = tcp_sndbuf(socket->pcb.tcp); - - if (available == 0) { - // Non-blocking socket - if (socket->timeout == 0) { - *_errno = MP_EAGAIN; - return MP_STREAM_ERROR; - } - - mp_uint_t start = mp_hal_ticks_ms(); - // Assume that STATE_PEER_CLOSED may mean half-closed connection, where peer closed it - // sending direction, but not receiving. Consequently, check for both STATE_CONNECTED - // and STATE_PEER_CLOSED as normal conditions and still waiting for buffers to be sent. - // If peer fully closed socket, we would have socket->state set to ERR_RST (connection - // reset) by error callback. - // Avoid sending too small packets, so wait until at least 16 bytes available - while (socket->state >= STATE_CONNECTED && (available = tcp_sndbuf(socket->pcb.tcp)) < 16) { - if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { - *_errno = MP_ETIMEDOUT; - return MP_STREAM_ERROR; - } - poll_sockets(); - } - - // While we waited, something could happen - STREAM_ERROR_CHECK(socket); - } - - u16_t write_len = MIN(available, len); - - err_t err = tcp_write(socket->pcb.tcp, buf, write_len, TCP_WRITE_FLAG_COPY); - - // If the output buffer is getting full then send the data to the lower layers - if (err == ERR_OK && tcp_sndbuf(socket->pcb.tcp) < TCP_SND_BUF / 4) { - err = tcp_output(socket->pcb.tcp); - } - - if (err != ERR_OK) { - *_errno = error_lookup_table[-err]; - return MP_STREAM_ERROR; - } - - return write_len; -} - -// Helper function for recv/recvfrom to handle TCP packets -STATIC mp_uint_t lwip_tcp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, int *_errno) { - // Check for any pending errors - STREAM_ERROR_CHECK(socket); - - if (socket->incoming.pbuf == NULL) { - - // Non-blocking socket - if (socket->timeout == 0) { - if (socket->state == STATE_PEER_CLOSED) { - return 0; - } - *_errno = MP_EAGAIN; - return -1; - } - - mp_uint_t start = mp_hal_ticks_ms(); - while (socket->state == STATE_CONNECTED && socket->incoming.pbuf == NULL) { - if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { - *_errno = MP_ETIMEDOUT; - return -1; - } - poll_sockets(); - } - - if (socket->state == STATE_PEER_CLOSED) { - if (socket->incoming.pbuf == NULL) { - // socket closed and no data left in buffer - return 0; - } - } else if (socket->state != STATE_CONNECTED) { - assert(socket->state < 0); - *_errno = error_lookup_table[-socket->state]; - return -1; - } - } - - assert(socket->pcb.tcp != NULL); - - struct pbuf *p = socket->incoming.pbuf; - - mp_uint_t remaining = p->len - socket->recv_offset; - if (len > remaining) { - len = remaining; - } - - memcpy(buf, (byte*)p->payload + socket->recv_offset, len); - - remaining -= len; - if (remaining == 0) { - socket->incoming.pbuf = p->next; - // If we don't ref here, free() will free the entire chain, - // if we ref, it does what we need: frees 1st buf, and decrements - // next buf's refcount back to 1. - pbuf_ref(p->next); - pbuf_free(p); - socket->recv_offset = 0; - } else { - socket->recv_offset += len; - } - tcp_recved(socket->pcb.tcp, len); - - return len; -} - -/*******************************************************************************/ -// The socket functions provided by lwip.socket. - -STATIC const mp_obj_type_t lwip_socket_type; - -STATIC void lwip_socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - lwip_socket_obj_t *self = self_in; - mp_printf(print, "", self->state, self->timeout, - self->incoming.pbuf, self->recv_offset); -} - -// FIXME: Only supports two arguments at present -STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_arg_check_num(n_args, n_kw, 0, 4, false); - - lwip_socket_obj_t *socket = m_new_obj_with_finaliser(lwip_socket_obj_t); - socket->base.type = (mp_obj_t)&lwip_socket_type; - socket->domain = MOD_NETWORK_AF_INET; - socket->type = MOD_NETWORK_SOCK_STREAM; - socket->callback = MP_OBJ_NULL; - if (n_args >= 1) { - socket->domain = mp_obj_get_int(args[0]); - if (n_args >= 2) { - socket->type = mp_obj_get_int(args[1]); - } - } - - 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); - } - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_ENOMEM); - } - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - // Register the socket object as our callback argument. - tcp_arg(socket->pcb.tcp, (void*)socket); - // Register our error callback. - tcp_err(socket->pcb.tcp, _lwip_tcp_error); - break; - } - 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); - break; - } - } - - socket->incoming.pbuf = NULL; - socket->timeout = -1; - socket->state = STATE_NEW; - socket->recv_offset = 0; - return socket; -} - -STATIC mp_obj_t lwip_socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - ip_addr_t bind_addr; - IP4_ADDR(&bind_addr, ip[0], ip[1], ip[2], ip[3]); - - err_t err = ERR_ARG; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - err = tcp_bind(socket->pcb.tcp, &bind_addr, port); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - err = udp_bind(socket->pcb.udp, &bind_addr, port); - break; - } - } - - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_bind_obj, lwip_socket_bind); - -STATIC mp_obj_t lwip_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { - lwip_socket_obj_t *socket = self_in; - mp_int_t backlog = mp_obj_get_int(backlog_in); - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - if (socket->type != MOD_NETWORK_SOCK_STREAM) { - mp_raise_OSError(MP_EOPNOTSUPP); - } - - struct tcp_pcb *new_pcb = tcp_listen_with_backlog(socket->pcb.tcp, (u8_t)backlog); - if (new_pcb == NULL) { - mp_raise_OSError(MP_ENOMEM); - } - socket->pcb.tcp = new_pcb; - tcp_accept(new_pcb, _lwip_tcp_accept); - - // Socket is no longer considered "new" for purposes of polling - socket->state = STATE_CONNECTING; - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_listen_obj, lwip_socket_listen); - -STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { - lwip_socket_obj_t *socket = self_in; - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - if (socket->type != MOD_NETWORK_SOCK_STREAM) { - mp_raise_OSError(MP_EOPNOTSUPP); - } - // I need to do this because "tcp_accepted", later, is a macro. - struct tcp_pcb *listener = socket->pcb.tcp; - if (listener->state != LISTEN) { - mp_raise_OSError(MP_EINVAL); - } - - // accept incoming connection - if (socket->incoming.connection == NULL) { - if (socket->timeout == 0) { - mp_raise_OSError(MP_EAGAIN); - } 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) { - mp_raise_OSError(MP_ETIMEDOUT); - } - } else { - while (socket->incoming.connection == NULL) { - poll_sockets(); - } - } - } - - // create new socket object - lwip_socket_obj_t *socket2 = m_new_obj_with_finaliser(lwip_socket_obj_t); - socket2->base.type = (mp_obj_t)&lwip_socket_type; - - // We get a new pcb handle... - socket2->pcb.tcp = socket->incoming.connection; - socket->incoming.connection = NULL; - - // ...and set up the new socket for it. - socket2->domain = MOD_NETWORK_AF_INET; - socket2->type = MOD_NETWORK_SOCK_STREAM; - socket2->incoming.pbuf = NULL; - socket2->timeout = socket->timeout; - socket2->state = STATE_CONNECTED; - socket2->recv_offset = 0; - socket2->callback = MP_OBJ_NULL; - tcp_arg(socket2->pcb.tcp, (void*)socket2); - tcp_err(socket2->pcb.tcp, _lwip_tcp_error); - tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv); - - tcp_accepted(listener); - - // make the return value - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - memcpy(ip, &(socket2->pcb.tcp->remote_ip), sizeof(ip)); - mp_uint_t port = (mp_uint_t)socket2->pcb.tcp->remote_port; - mp_obj_tuple_t *client = mp_obj_new_tuple(2, NULL); - client->items[0] = socket2; - client->items[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); - - return client; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_socket_accept_obj, lwip_socket_accept); - -STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - - if (socket->pcb.tcp == NULL) { - mp_raise_OSError(MP_EBADF); - } - - // get address - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - ip_addr_t dest; - IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); - - err_t err = ERR_ARG; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->state != STATE_NEW) { - if (socket->state == STATE_CONNECTED) { - mp_raise_OSError(MP_EISCONN); - } else { - mp_raise_OSError(MP_EALREADY); - } - } - // Register our receive callback. - tcp_recv(socket->pcb.tcp, _lwip_tcp_recv); - socket->state = STATE_CONNECTING; - err = tcp_connect(socket->pcb.tcp, &dest, port, _lwip_tcp_connected); - if (err != ERR_OK) { - socket->state = STATE_NEW; - mp_raise_OSError(error_lookup_table[-err]); - } - socket->peer_port = (mp_uint_t)port; - memcpy(socket->peer, &dest, sizeof(socket->peer)); - // And now we wait... - 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) { - mp_raise_OSError(MP_EINPROGRESS); - } - } else { - while (socket->state == STATE_CONNECTING) { - poll_sockets(); - } - } - if (socket->state == STATE_CONNECTED) { - err = ERR_OK; - } else { - err = socket->state; - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - err = udp_connect(socket->pcb.udp, &dest, port); - break; - } - } - - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_connect_obj, lwip_socket_connect); - -STATIC void lwip_socket_check_connected(lwip_socket_obj_t *socket) { - if (socket->pcb.tcp == NULL) { - // not connected - int _errno = error_lookup_table[-socket->state]; - socket->state = _ERR_BADF; - mp_raise_OSError(_errno); - } -} - -STATIC mp_obj_t lwip_socket_send(mp_obj_t self_in, mp_obj_t buf_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_send(socket, bufinfo.buf, bufinfo.len, NULL, 0, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - return mp_obj_new_int_from_uint(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_send_obj, lwip_socket_send); - -STATIC mp_obj_t lwip_socket_recv(mp_obj_t self_in, mp_obj_t len_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_int_t len = mp_obj_get_int(len_in); - vstr_t vstr; - vstr_init_len(&vstr, len); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - 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); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - if (ret == 0) { - return mp_const_empty_bytes; - } - vstr.len = ret; - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recv_obj, lwip_socket_recv); - -STATIC mp_obj_t lwip_socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_READ); - - uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_send(socket, bufinfo.buf, bufinfo.len, ip, port, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - return mp_obj_new_int_from_uint(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(lwip_socket_sendto_obj, lwip_socket_sendto); - -STATIC mp_obj_t lwip_socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { - lwip_socket_obj_t *socket = self_in; - int _errno; - - lwip_socket_check_connected(socket); - - mp_int_t len = mp_obj_get_int(len_in); - vstr_t vstr; - vstr_init_len(&vstr, len); - byte ip[4]; - mp_uint_t port; - - mp_uint_t ret = 0; - 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); - break; - } - case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte*)vstr.buf, len, ip, &port, &_errno); - break; - } - } - if (ret == -1) { - mp_raise_OSError(_errno); - } - - mp_obj_t tuple[2]; - if (ret == 0) { - tuple[0] = mp_const_empty_bytes; - } else { - vstr.len = ret; - tuple[0] = mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); - } - tuple[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); - return mp_obj_new_tuple(2, tuple); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recvfrom_obj, lwip_socket_recvfrom); - -STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) { - lwip_socket_obj_t *socket = self_in; - lwip_socket_check_connected(socket); - - int _errno; - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - - mp_uint_t ret = 0; - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->timeout == 0) { - // Behavior of sendall() for non-blocking sockets isn't explicitly specified. - // But it's specified that "On error, an exception is raised, there is no - // way to determine how much data, if any, was successfully sent." Then, the - // most useful behavior is: check whether we will be able to send all of input - // data without EAGAIN, and if won't be, raise it without sending any. - if (bufinfo.len > tcp_sndbuf(socket->pcb.tcp)) { - mp_raise_OSError(MP_EAGAIN); - } - } - // TODO: In CPython3.5, socket timeout should apply to the - // entire sendall() operation, not to individual send() chunks. - while (bufinfo.len != 0) { - ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); - if (ret == -1) { - mp_raise_OSError(_errno); - } - bufinfo.len -= ret; - bufinfo.buf = (char*)bufinfo.buf + ret; - } - break; - } - case MOD_NETWORK_SOCK_DGRAM: - mp_raise_NotImplementedError(NULL); - break; - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_sendall_obj, lwip_socket_sendall); - -STATIC mp_obj_t lwip_socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { - lwip_socket_obj_t *socket = self_in; - mp_uint_t timeout; - if (timeout_in == mp_const_none) { - timeout = -1; - } else { - #if MICROPY_PY_BUILTINS_FLOAT - timeout = 1000 * mp_obj_get_float(timeout_in); - #else - timeout = 1000 * mp_obj_get_int(timeout_in); - #endif - } - socket->timeout = timeout; - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_settimeout_obj, lwip_socket_settimeout); - -STATIC mp_obj_t lwip_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { - lwip_socket_obj_t *socket = self_in; - bool val = mp_obj_is_true(flag_in); - if (val) { - socket->timeout = -1; - } else { - socket->timeout = 0; - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_setblocking_obj, lwip_socket_setblocking); - -STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) { - (void)n_args; // always 4 - lwip_socket_obj_t *socket = args[0]; - - int opt = mp_obj_get_int(args[2]); - if (opt == 20) { - if (args[3] == mp_const_none) { - socket->callback = MP_OBJ_NULL; - } else { - socket->callback = args[3]; - } - return mp_const_none; - } - - switch (opt) { - // level: SOL_SOCKET - case SOF_REUSEADDR: { - mp_int_t val = mp_obj_get_int(args[3]); - // Options are common for UDP and TCP pcb's. - if (val) { - ip_set_option(socket->pcb.tcp, SOF_REUSEADDR); - } else { - ip_reset_option(socket->pcb.tcp, SOF_REUSEADDR); - } - break; - } - - // level: IPPROTO_IP - case IP_ADD_MEMBERSHIP: { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); - if (bufinfo.len != sizeof(ip_addr_t) * 2) { - mp_raise_ValueError(NULL); - } - - // 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); - if (err != ERR_OK) { - mp_raise_OSError(error_lookup_table[-err]); - } - break; - } - - default: - printf("Warning: lwip.setsockopt() not implemented\n"); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_setsockopt_obj, 4, 4, lwip_socket_setsockopt); - -STATIC mp_obj_t lwip_socket_makefile(size_t n_args, const mp_obj_t *args) { - (void)n_args; - return args[0]; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_makefile_obj, 1, 3, lwip_socket_makefile); - -STATIC mp_uint_t lwip_socket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { - lwip_socket_obj_t *socket = self_in; - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - return lwip_tcp_receive(socket, buf, size, errcode); - case MOD_NETWORK_SOCK_DGRAM: - return lwip_udp_receive(socket, buf, size, NULL, NULL, errcode); - } - // Unreachable - return MP_STREAM_ERROR; -} - -STATIC mp_uint_t lwip_socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { - lwip_socket_obj_t *socket = self_in; - - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: - return lwip_tcp_send(socket, buf, size, errcode); - case MOD_NETWORK_SOCK_DGRAM: - return lwip_udp_send(socket, buf, size, NULL, 0, errcode); - } - // Unreachable - return MP_STREAM_ERROR; -} - -STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { - lwip_socket_obj_t *socket = self_in; - mp_uint_t ret; - - if (request == MP_STREAM_POLL) { - uintptr_t flags = arg; - ret = 0; - - if (flags & MP_STREAM_POLL_RD && socket->incoming.pbuf != NULL) { - ret |= MP_STREAM_POLL_RD; - } - - // Note: pcb.tcp==NULL if state<0, and in this case we can't call tcp_sndbuf - if (flags & MP_STREAM_POLL_WR && socket->pcb.tcp != NULL && tcp_sndbuf(socket->pcb.tcp) > 0) { - ret |= MP_STREAM_POLL_WR; - } - - if (socket->state == STATE_NEW) { - // New sockets are not connected so set HUP - ret |= flags & MP_STREAM_POLL_HUP; - } else if (socket->state == STATE_PEER_CLOSED) { - // Peer-closed socket is both readable and writable: read will - // return EOF, write - error. Without this poll will hang on a - // socket which was closed by peer. - ret |= flags & (MP_STREAM_POLL_RD | MP_STREAM_POLL_WR); - } else if (socket->state == ERR_RST) { - // Socket was reset by peer, a write will return an error - ret |= flags & (MP_STREAM_POLL_WR | MP_STREAM_POLL_HUP); - } else if (socket->state < 0) { - // Socket in some other error state, use catch-all ERR flag - // TODO: may need to set other return flags here - ret |= flags & MP_STREAM_POLL_ERR; - } - - } else if (request == MP_STREAM_CLOSE) { - bool socket_is_listener = false; - - if (socket->pcb.tcp == NULL) { - return 0; - } - switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: { - if (socket->pcb.tcp->state == LISTEN) { - socket_is_listener = true; - } - if (tcp_close(socket->pcb.tcp) != ERR_OK) { - DEBUG_printf("lwip_close: had to call tcp_abort()\n"); - tcp_abort(socket->pcb.tcp); - } - 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; - if (socket->incoming.pbuf != NULL) { - if (!socket_is_listener) { - pbuf_free(socket->incoming.pbuf); - } else { - tcp_abort(socket->incoming.connection); - } - socket->incoming.pbuf = NULL; - } - ret = 0; - - } else { - *errcode = MP_EINVAL; - ret = MP_STREAM_ERROR; - } - - return ret; -} - -STATIC const mp_rom_map_elem_t lwip_socket_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&lwip_socket_bind_obj) }, - { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&lwip_socket_listen_obj) }, - { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&lwip_socket_accept_obj) }, - { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&lwip_socket_connect_obj) }, - { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&lwip_socket_send_obj) }, - { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&lwip_socket_recv_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&lwip_socket_sendto_obj) }, - { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&lwip_socket_recvfrom_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendall), MP_ROM_PTR(&lwip_socket_sendall_obj) }, - { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&lwip_socket_settimeout_obj) }, - { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&lwip_socket_setblocking_obj) }, - { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&lwip_socket_setsockopt_obj) }, - { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&lwip_socket_makefile_obj) }, - - { 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) }, - { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, -}; -STATIC MP_DEFINE_CONST_DICT(lwip_socket_locals_dict, lwip_socket_locals_dict_table); - -STATIC const mp_stream_p_t lwip_socket_stream_p = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_stream) - .read = lwip_socket_read, - .write = lwip_socket_write, - .ioctl = lwip_socket_ioctl, -}; - -STATIC const mp_obj_type_t lwip_socket_type = { - { &mp_type_type }, - .name = MP_QSTR_socket, - .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, -}; - -/******************************************************************************/ -// Support functions for memory protection. lwIP has its own memory management -// routines for its internal structures, and since they might be called in -// interrupt handlers, they need some protection. -sys_prot_t sys_arch_protect() { - return (sys_prot_t)MICROPY_BEGIN_ATOMIC_SECTION(); -} - -void sys_arch_unprotect(sys_prot_t state) { - MICROPY_END_ATOMIC_SECTION((mp_uint_t)state); -} - -/******************************************************************************/ -// Polling callbacks for the interfaces connected to lwIP. Right now it calls -// itself a "list" but isn't; we only support a single interface. - -typedef struct nic_poll { - 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) { - lwip_poll_list.poll = poll; - lwip_poll_list.poll_arg = poll_arg; -} - -void mod_lwip_deregister_poll(void (* poll)(void *arg), void *poll_arg) { - lwip_poll_list.poll = NULL; -} - -/******************************************************************************/ -// The lwip global functions. - -STATIC mp_obj_t mod_lwip_reset() { - lwip_init(); - lwip_poll_list.poll = NULL; - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_reset_obj, mod_lwip_reset); - -STATIC mp_obj_t mod_lwip_callback() { - if (lwip_poll_list.poll != NULL) { - lwip_poll_list.poll(lwip_poll_list.poll_arg); - } - sys_check_timeouts(); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_callback_obj, mod_lwip_callback); - -typedef struct _getaddrinfo_state_t { - volatile int status; - volatile ip_addr_t ipaddr; -} getaddrinfo_state_t; - -// Callback for incoming DNS requests. -#if LWIP_VERSION_MAJOR < 2 -STATIC void lwip_getaddrinfo_cb(const char *name, ip_addr_t *ipaddr, void *arg) -#else -STATIC void lwip_getaddrinfo_cb(const char *name, const ip_addr_t *ipaddr, void *arg) -#endif -{ - getaddrinfo_state_t *state = arg; - if (ipaddr != NULL) { - state->status = 1; - state->ipaddr = *ipaddr; - } else { - // error - state->status = -2; - } -} - -// lwip.getaddrinfo -STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { - mp_obj_t host_in = args[0], port_in = args[1]; - const char *host = mp_obj_str_get_str(host_in); - mp_int_t port = mp_obj_get_int(port_in); - - // If constraints were passed then check they are compatible with the supported params - if (n_args > 2) { - mp_int_t family = mp_obj_get_int(args[2]); - mp_int_t type = 0; - mp_int_t proto = 0; - mp_int_t flags = 0; - if (n_args > 3) { - type = mp_obj_get_int(args[3]); - if (n_args > 4) { - proto = mp_obj_get_int(args[4]); - if (n_args > 5) { - flags = mp_obj_get_int(args[5]); - } - } - } - if (!((family == 0 || family == MOD_NETWORK_AF_INET) - && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) - && proto == 0 - && flags == 0)) { - mp_warning("unsupported getaddrinfo constraints"); - } - } - - getaddrinfo_state_t state; - state.status = 0; - - err_t ret = dns_gethostbyname(host, (ip_addr_t*)&state.ipaddr, lwip_getaddrinfo_cb, &state); - switch (ret) { - case ERR_OK: - // cached - state.status = 1; - break; - case ERR_INPROGRESS: - while (state.status == 0) { - poll_sockets(); - } - break; - default: - state.status = ret; - } - - if (state.status < 0) { - // TODO: CPython raises gaierror, we raise with native lwIP negative error - // values, to differentiate from normal errno's at least in such way. - mp_raise_OSError(state.status); - } - - mp_obj_tuple_t *tuple = mp_obj_new_tuple(5, NULL); - tuple->items[0] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_AF_INET); - 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); -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo); - -// Debug functions - -STATIC mp_obj_t lwip_print_pcbs() { - tcp_debug_print_pcbs(); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_0(lwip_print_pcbs_obj, lwip_print_pcbs); - -#if MICROPY_PY_LWIP - -STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_lwip) }, - { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&mod_lwip_reset_obj) }, - { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&mod_lwip_callback_obj) }, - { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&lwip_getaddrinfo_obj) }, - { 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 - { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) }, -#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) }, - - { MP_ROM_QSTR(MP_QSTR_SOCK_STREAM), MP_ROM_INT(MOD_NETWORK_SOCK_STREAM) }, - { MP_ROM_QSTR(MP_QSTR_SOCK_DGRAM), MP_ROM_INT(MOD_NETWORK_SOCK_DGRAM) }, - { MP_ROM_QSTR(MP_QSTR_SOCK_RAW), MP_ROM_INT(MOD_NETWORK_SOCK_RAW) }, - - { MP_ROM_QSTR(MP_QSTR_SOL_SOCKET), MP_ROM_INT(1) }, - { MP_ROM_QSTR(MP_QSTR_SO_REUSEADDR), MP_ROM_INT(SOF_REUSEADDR) }, - - { MP_ROM_QSTR(MP_QSTR_IPPROTO_IP), MP_ROM_INT(0) }, - { MP_ROM_QSTR(MP_QSTR_IP_ADD_MEMBERSHIP), MP_ROM_INT(IP_ADD_MEMBERSHIP) }, -}; - -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, -}; - -#endif // MICROPY_PY_LWIP diff --git a/extmod/modonewire.c b/extmod/modonewire.c index 1b085a0555611..edb7e23cea911 100644 --- a/extmod/modonewire.c +++ b/extmod/modonewire.c @@ -13,8 +13,8 @@ // Low-level 1-Wire routines #define TIMING_RESET1 (480) -#define TIMING_RESET2 (40) -#define TIMING_RESET3 (420) +#define TIMING_RESET2 (70) +#define TIMING_RESET3 (410) #define TIMING_READ1 (5) #define TIMING_READ2 (5) #define TIMING_READ3 (40) @@ -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 32c36eea6dde0..91df02317eff8 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 dc8ac4c7219e9..d093d3978791b 100644 --- a/extmod/moductypes.c +++ b/extmod/moductypes.c @@ -1,4 +1,4 @@ -// Copyright (c) 2014 Paul Sokolovsky +// Copyright (c) 2014-2018 Paul Sokolovsky // SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) // // SPDX-License-Identifier: MIT @@ -73,7 +73,7 @@ enum { #define AGG_TYPE_BITS 2 enum { - STRUCT, PTR, ARRAY, BITFIELD, + STRUCT, PTR, ARRAY, }; // Here we need to set sign bit right @@ -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) { @@ -118,15 +118,23 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p (void)kind; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); const char *typen = "unk"; - if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) { + if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + || MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + #endif + ) { typen = "STRUCT"; } else if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); 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 +165,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); @@ -187,9 +195,13 @@ 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_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + && !MP_OBJ_IS_TYPE(desc_in, &mp_type_ordereddict) + #endif + ) { 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 @@ -242,7 +254,8 @@ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_ return total_size; } -STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) { +STATIC mp_obj_t uctypes_struct_sizeof(size_t n_args, const mp_obj_t *args) { + mp_obj_t obj_in = args[0]; mp_uint_t max_field_size = 0; if (MP_OBJ_IS_TYPE(obj_in, &mp_type_bytearray)) { return mp_obj_len(obj_in); @@ -251,15 +264,22 @@ STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) { // We can apply sizeof either to structure definition (a dict) // or to instantiated structure if (MP_OBJ_IS_TYPE(obj_in, &uctypes_struct_type)) { + if (n_args != 1) { + mp_raise_TypeError(NULL); + } // Extract structure definition mp_obj_uctypes_struct_t *obj = MP_OBJ_TO_PTR(obj_in); obj_in = obj->desc; layout_type = obj->flags; + } else { + if (n_args == 2) { + layout_type = mp_obj_get_int(args[1]); + } } mp_uint_t size = uctypes_struct_size(obj_in, layout_type, &max_field_size); return MP_OBJ_NEW_SMALL_INT(size); } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_sizeof_obj, uctypes_struct_sizeof); +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(uctypes_struct_sizeof_obj, 1, 2, uctypes_struct_sizeof); static inline mp_obj_t get_unaligned(uint val_type, byte *p, int big_endian) { char struct_type = big_endian ? '>' : '<'; @@ -276,11 +296,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 +309,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 +324,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(((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 +356,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 +366,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); @@ -371,9 +400,12 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set_val) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); - // TODO: Support at least OrderedDict in addition - if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) { - mp_raise_TypeError(translate("struct: no fields")); + if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + && !MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + #endif + ) { + mp_raise_TypeError(translate("struct: no fields")); } mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr)); @@ -381,7 +413,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 +483,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 +507,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 +587,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); @@ -576,6 +608,26 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t base_in, mp_obj_t index_in, mp_ob } } +STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) { + mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); + switch (op) { + case MP_UNARY_OP_INT: + if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); + mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); + uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); + if (agg_type == PTR) { + byte *p = *(void **)self->addr; + return mp_obj_new_int((mp_int_t)(uintptr_t)p); + } + } + /* fallthru */ + + default: + return MP_OBJ_NULL; // op not supported + } +} + STATIC mp_int_t uctypes_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { (void)flags; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); @@ -603,7 +655,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 +664,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); @@ -624,6 +676,7 @@ STATIC const mp_obj_type_t uctypes_struct_type = { .make_new = uctypes_struct_make_new, .attr = uctypes_struct_attr, .subscr = uctypes_struct_subscr, + .unary_op = uctypes_struct_unary_op, .buffer_p = { .get_buffer = uctypes_get_buffer }, }; @@ -682,6 +735,30 @@ STATIC const mp_rom_map_elem_t mp_module_uctypes_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_FLOAT64), MP_ROM_INT(TYPE2SMALLINT(FLOAT64, 4)) }, #endif + #if MICROPY_PY_UCTYPES_NATIVE_C_TYPES + // C native type aliases. These depend on GCC-compatible predefined + // preprocessor macros. + #if __SIZEOF_SHORT__ == 2 + { MP_ROM_QSTR(MP_QSTR_SHORT), MP_ROM_INT(TYPE2SMALLINT(INT16, 4)) }, + { MP_ROM_QSTR(MP_QSTR_USHORT), MP_ROM_INT(TYPE2SMALLINT(UINT16, 4)) }, + #endif + #if __SIZEOF_INT__ == 4 + { MP_ROM_QSTR(MP_QSTR_INT), MP_ROM_INT(TYPE2SMALLINT(INT32, 4)) }, + { MP_ROM_QSTR(MP_QSTR_UINT), MP_ROM_INT(TYPE2SMALLINT(UINT32, 4)) }, + #endif + #if __SIZEOF_LONG__ == 4 + { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT32, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT32, 4)) }, + #elif __SIZEOF_LONG__ == 8 + { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT64, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, 4)) }, + #endif + #if __SIZEOF_LONG_LONG__ == 8 + { MP_ROM_QSTR(MP_QSTR_LONGLONG), MP_ROM_INT(TYPE2SMALLINT(INT64, 4)) }, + { MP_ROM_QSTR(MP_QSTR_ULONGLONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, 4)) }, + #endif + #endif // MICROPY_PY_UCTYPES_NATIVE_C_TYPES + { MP_ROM_QSTR(MP_QSTR_PTR), MP_ROM_INT(TYPE2SMALLINT(PTR, AGG_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_ARRAY), MP_ROM_INT(TYPE2SMALLINT(ARRAY, AGG_TYPE_BITS)) }, }; @@ -690,7 +767,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 95485de138fd9..7069cc4792650 100644 --- a/extmod/moduhashlib.c +++ b/extmod/moduhashlib.c @@ -12,6 +12,10 @@ #if MICROPY_PY_UHASHLIB +#if MICROPY_SSL_MBEDTLS +#include "mbedtls/version.h" +#endif + #if MICROPY_PY_UHASHLIB_SHA256 #if MICROPY_SSL_MBEDTLS @@ -22,13 +26,14 @@ #endif -#if MICROPY_PY_UHASHLIB_SHA1 +#if MICROPY_PY_UHASHLIB_SHA1 || MICROPY_PY_UHASHLIB_MD5 #if MICROPY_SSL_AXTLS #include "lib/axtls/crypto/crypto.h" #endif #if MICROPY_SSL_MBEDTLS +#include "mbedtls/md5.h" #include "mbedtls/sha1.h" #endif @@ -45,12 +50,18 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg); #if MICROPY_SSL_MBEDTLS -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); +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_sha256_starts_ret mbedtls_sha256_starts +#define mbedtls_sha256_update_ret mbedtls_sha256_update +#define mbedtls_sha256_finish_ret mbedtls_sha256_finish +#endif + +STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *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_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_ret((mbedtls_sha256_context *)&o->state, 0); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -61,7 +72,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_ret((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -69,25 +80,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_ret((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 +110,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 +118,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 +137,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 +149,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 +161,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,18 +169,25 @@ 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 #if MICROPY_SSL_MBEDTLS + +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_sha1_starts_ret mbedtls_sha1_starts +#define mbedtls_sha1_update_ret mbedtls_sha1_update +#define mbedtls_sha1_finish_ret mbedtls_sha1_finish +#endif + STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *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_ret((mbedtls_sha1_context *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -180,7 +198,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_ret((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -188,8 +206,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_ret((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,10 +225,97 @@ 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 +#if MICROPY_PY_UHASHLIB_MD5 +STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg); + +#if MICROPY_SSL_AXTLS +STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *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(MD5_CTX)); + o->base.type = type; + MD5_Init((MD5_CTX *)o->state); + if (n_args == 1) { + uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); + } + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_obj_t uhashlib_md5_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); + MD5_Update((MD5_CTX *)self->state, bufinfo.buf, bufinfo.len); + return mp_const_none; +} + +STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + vstr_t vstr; + vstr_init_len(&vstr, MD5_SIZE); + MD5_Final((byte *)vstr.buf, (MD5_CTX *)self->state); + return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); +} +#endif // MICROPY_SSL_AXTLS + +#if MICROPY_SSL_MBEDTLS + +#if MBEDTLS_VERSION_NUMBER < 0x02070000 +#define mbedtls_md5_starts_ret mbedtls_md5_starts +#define mbedtls_md5_update_ret mbedtls_md5_update +#define mbedtls_md5_finish_ret mbedtls_md5_finish +#endif + +STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *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_md5_context)); + o->base.type = type; + mbedtls_md5_init((mbedtls_md5_context *)o->state); + mbedtls_md5_starts_ret((mbedtls_md5_context *)o->state); + if (n_args == 1) { + uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); + } + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_obj_t uhashlib_md5_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_md5_update_ret((mbedtls_md5_context *)self->state, bufinfo.buf, bufinfo.len); + return mp_const_none; +} + +STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { + mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); + vstr_t vstr; + vstr_init_len(&vstr, 16); + mbedtls_md5_finish_ret((mbedtls_md5_context *)self->state, (byte *)vstr.buf); + mbedtls_md5_free((mbedtls_md5_context *)self->state); + return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); +} +#endif // MICROPY_SSL_MBEDTLS + +STATIC MP_DEFINE_CONST_FUN_OBJ_2(uhashlib_md5_update_obj, uhashlib_md5_update); +STATIC MP_DEFINE_CONST_FUN_OBJ_1(uhashlib_md5_digest_obj, uhashlib_md5_digest); + +STATIC const mp_rom_map_elem_t uhashlib_md5_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&uhashlib_md5_update_obj) }, + { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&uhashlib_md5_digest_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(uhashlib_md5_locals_dict, uhashlib_md5_locals_dict_table); + +STATIC const mp_obj_type_t uhashlib_md5_type = { + { &mp_type_type }, + .name = MP_QSTR_md5, + .make_new = uhashlib_md5_make_new, + .locals_dict = (void *)&uhashlib_md5_locals_dict, +}; +#endif // MICROPY_PY_UHASHLIB_MD5 + STATIC const mp_rom_map_elem_t mp_module_uhashlib_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hashlib) }, #if MICROPY_PY_UHASHLIB_SHA256 @@ -219,17 +324,20 @@ STATIC const mp_rom_map_elem_t mp_module_uhashlib_globals_table[] = { #if MICROPY_PY_UHASHLIB_SHA1 { MP_ROM_QSTR(MP_QSTR_sha1), MP_ROM_PTR(&uhashlib_sha1_type) }, #endif + #if MICROPY_PY_UHASHLIB_MD5 + { MP_ROM_QSTR(MP_QSTR_md5), MP_ROM_PTR(&uhashlib_md5_type) }, + #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_uhashlib_globals, mp_module_uhashlib_globals_table); 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 50fe6c0513d86..9e02d367a23c6 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 3bb4b33017d60..63e8a011bf6b9 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 a60250efc8b99..26e89f77f236c 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; - - return (yasmarang_pad^(yasmarang_d<<5)^(yasmarang_pad>>18)^(yasmarang_dat<<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); } /* 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 bb54bc732f5b5..0238c196b6f53 100644 --- a/extmod/modure.c +++ b/extmod/modure.c @@ -18,7 +18,9 @@ #include "re1.5/re1.5.h" +#if CIRCUITPY_RE_DEBUG #define FLAG_DEBUG 0x1000 +#endif typedef struct _mp_obj_re_t { mp_obj_base_t base; @@ -52,7 +54,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 +143,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 +159,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 +187,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 +229,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 +240,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 +251,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 +280,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 +304,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 +386,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) { @@ -401,18 +403,24 @@ STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { } mp_obj_re_t *o = m_new_obj_var(mp_obj_re_t, char, size); o->base.type = &re_type; + #if CIRCUITPY_RE_DEBUG int flags = 0; if (n_args > 1) { flags = mp_obj_get_int(args[1]); } + #else + (void)n_args; + #endif int error = re1_5_compilecode(&o->re, re_str); if (error != 0) { -error: + error: mp_raise_ValueError(translate("Error in regex")); } + #if CIRCUITPY_RE_DEBUG if (flags & FLAG_DEBUG) { re1_5_dumpcode(&o->re); } + #endif return MP_OBJ_FROM_PTR(o); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_re_compile_obj, 1, 2, mod_re_compile); @@ -445,25 +453,27 @@ 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) }, #if MICROPY_PY_URE_SUB { MP_ROM_QSTR(MP_QSTR_sub), MP_ROM_PTR(&mod_re_sub_obj) }, #endif + #if CIRCUITPY_RE_DEBUG { MP_ROM_QSTR(MP_QSTR_DEBUG), MP_ROM_INT(FLAG_DEBUG) }, + #endif }; 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 @@ -471,8 +481,10 @@ const mp_obj_module_t mp_module_ure = { #define re1_5_fatal(x) assert(!x) #include "re1.5/compilecode.c" +#if CIRCUITPY_RE_DEBUG #include "re1.5/dumpcode.c" +#endif #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 97b14a5f25e4b..e88494b279700 100644 --- a/extmod/moduselect.c +++ b/extmod/moduselect.c @@ -25,7 +25,7 @@ typedef struct _poll_obj_t { mp_obj_t obj; - mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, mp_uint_t arg, int *errcode); + mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); mp_uint_t flags; mp_uint_t flags_ret; } poll_obj_t; @@ -33,7 +33,7 @@ typedef struct _poll_obj_t { STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_len, mp_uint_t flags, bool or_flags) { for (mp_uint_t i = 0; i < obj_len; i++) { mp_map_elem_t *elem = mp_map_lookup(poll_map, mp_obj_id(obj[i]), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); - if (elem->value == NULL) { + if (elem->value == MP_OBJ_NULL) { // object not found; get its ioctl and add it to the poll list const mp_stream_p_t *stream_p = mp_get_stream_raise(obj[i], MP_STREAM_OP_IOCTL); poll_obj_t *poll_obj = m_new_obj(poll_obj_t); @@ -41,27 +41,27 @@ STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_ poll_obj->ioctl = stream_p->ioctl; poll_obj->flags = flags; poll_obj->flags_ret = 0; - elem->value = poll_obj; + elem->value = MP_OBJ_FROM_PTR(poll_obj); } else { // object exists; update its flags if (or_flags) { - ((poll_obj_t*)elem->value)->flags |= flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags |= flags; } else { - ((poll_obj_t*)elem->value)->flags = flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = flags; } } } } // poll each object in the map -STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, mp_uint_t *rwx_num) { +STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, size_t *rwx_num) { mp_uint_t n_ready = 0; for (mp_uint_t i = 0; i < poll_map->alloc; ++i) { 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 = MP_OBJ_TO_PTR(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 = MP_OBJ_TO_PTR(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 *)MP_OBJ_TO_PTR(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 *)MP_OBJ_TO_PTR(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 *)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj; } } mp_map_deinit(&poll_map); @@ -171,7 +171,7 @@ typedef struct _mp_obj_poll_t { /// \method register(obj[, eventmask]) STATIC mp_obj_t poll_register(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t flags; if (n_args == 3) { flags = mp_obj_get_int(args[2]); @@ -185,7 +185,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_register_obj, 2, 3, poll_register); /// \method unregister(obj) STATIC mp_obj_t poll_unregister(mp_obj_t self_in, mp_obj_t obj_in) { - mp_obj_poll_t *self = self_in; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP_REMOVE_IF_FOUND); // TODO raise KeyError if obj didn't exist in map return mp_const_none; @@ -194,18 +194,18 @@ MP_DEFINE_CONST_FUN_OBJ_2(poll_unregister_obj, poll_unregister); /// \method modify(obj, eventmask) STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmask_in) { - mp_obj_poll_t *self = self_in; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *elem = mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP); if (elem == NULL) { mp_raise_OSError(MP_ENOENT); } - ((poll_obj_t*)elem->value)->flags = mp_obj_get_int(eventmask_in); + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); STATIC mp_uint_t poll_poll_internal(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); // work out timeout (its given already in ms) mp_uint_t timeout = -1; @@ -238,18 +238,18 @@ STATIC mp_uint_t poll_poll_internal(uint n_args, const mp_obj_t *args) { return n_ready; } -STATIC mp_obj_t poll_poll(uint n_args, const mp_obj_t *args) { - mp_obj_poll_t *self = args[0]; +STATIC mp_obj_t poll_poll(size_t n_args, const mp_obj_t *args) { + mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t n_ready = poll_poll_internal(n_args, args); // one or more objects are ready, or we had a timeout - mp_obj_list_t *ret_list = mp_obj_new_list(n_ready, NULL); + mp_obj_list_t *ret_list = MP_OBJ_TO_PTR(mp_obj_new_list(n_ready, NULL)); n_ready = 0; for (mp_uint_t i = 0; i < self->poll_map.alloc; ++i) { 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 = MP_OBJ_TO_PTR(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); @@ -259,7 +259,7 @@ STATIC mp_obj_t poll_poll(uint n_args, const mp_obj_t *args) { } } } - return ret_list; + return MP_OBJ_FROM_PTR(ret_list); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_poll_obj, 1, 3, poll_poll); @@ -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 = MP_OBJ_TO_PTR(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() @@ -334,7 +334,7 @@ STATIC mp_obj_t select_poll(void) { mp_map_init(&poll->poll_map, 0); poll->iter_cnt = 0; poll->ret_tuple = MP_OBJ_NULL; - return poll; + return MP_OBJ_FROM_PTR(poll); } MP_DEFINE_CONST_FUN_OBJ_0(mp_select_poll_obj, select_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 7cc2bb3e25500..673f480b2cd16 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); @@ -158,21 +158,13 @@ STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); - (void)arg; - switch (request) { - case MP_STREAM_CLOSE: - if (self->ssl_sock != NULL) { - ssl_free(self->ssl_sock); - ssl_ctx_free(self->ssl_ctx); - self->ssl_sock = NULL; - mp_stream_close(self->sock); - } - return 0; - - default: - *errcode = MP_EINVAL; - return MP_STREAM_ERROR; + if (request == MP_STREAM_CLOSE && self->ssl_sock != NULL) { + ssl_free(self->ssl_sock); + ssl_ctx_free(self->ssl_ctx); + self->ssl_sock = NULL; } + // Pass all requests down to the underlying socket + return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { @@ -192,9 +184,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,16 +206,16 @@ 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) { // TODO: Implement more args static const mp_arg_t allowed_args[] = { - { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, + { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, }; // TODO: Check that sock implements stream protocol @@ -231,7 +223,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 +238,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 990523173dd9b..05d6047f9b763 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); @@ -249,23 +249,17 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); - (void)arg; - switch (request) { - case MP_STREAM_CLOSE: - mbedtls_pk_free(&self->pkey); - mbedtls_x509_crt_free(&self->cert); - mbedtls_x509_crt_free(&self->cacert); - mbedtls_ssl_free(&self->ssl); - mbedtls_ssl_config_free(&self->conf); - mbedtls_ctr_drbg_free(&self->ctr_drbg); - mbedtls_entropy_free(&self->entropy); - mp_stream_close(self->sock); - return 0; - - default: - *errcode = MP_EINVAL; - return MP_STREAM_ERROR; + if (request == MP_STREAM_CLOSE) { + mbedtls_pk_free(&self->pkey); + mbedtls_x509_crt_free(&self->cert); + mbedtls_x509_crt_free(&self->cacert); + mbedtls_ssl_free(&self->ssl); + mbedtls_ssl_config_free(&self->conf); + mbedtls_ctr_drbg_free(&self->ctr_drbg); + mbedtls_entropy_free(&self->entropy); } + // Pass all requests down to the underlying socket + return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { @@ -275,9 +269,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 +292,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 +309,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 +324,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 bb2b6b335d264..beeb4353d903c 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 b344f96429409..9c80f163227d3 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 5b3c6150a73d3..f470e26dbaca3 100644 --- a/extmod/modwebrepl.c +++ b/extmod/modwebrepl.c @@ -14,7 +14,6 @@ #include "py/mphal.h" #endif #include "extmod/modwebsocket.h" -#include "genhdr/mpversion.h" #if MICROPY_PY_WEBREPL @@ -127,7 +126,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 +160,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 +194,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 +216,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 +320,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 +333,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 581af6b58871b..6547ebee4430b 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 @@ STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int 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 @@ STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int } 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/re1.5/compilecode.c b/extmod/re1.5/compilecode.c index 01d3d149884eb..81c0bceef7732 100644 --- a/extmod/re1.5/compilecode.c +++ b/extmod/re1.5/compilecode.c @@ -8,9 +8,9 @@ ((code ? memmove(code + at + num, code + at, pc - at) : 0), pc += num) #define REL(at, to) (to - at - 2) #define EMIT(at, byte) (code ? (code[at] = byte) : (at)) +#define EMIT_CHECKED(at, byte) (_emit_checked(at, code, byte, &err)) #define PC (prog->bytelen) - static char unescape(char c) { switch (c) { case 'a': @@ -33,9 +33,17 @@ static char unescape(char c) { } +static void _emit_checked(int at, char *code, int val, bool *err) { + *err |= val != (int8_t)val; + if (code) { + code[at] = val; + } +} + static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) { char *code = sizecode ? NULL : prog->insts; + bool err = false; int start = PC; int term = PC; int alt_label = 0; @@ -96,7 +104,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) EMIT(PC++, *re); } } - EMIT(term + 1, cnt); + EMIT_CHECKED(term + 1, cnt); break; } case '(': { @@ -107,7 +115,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) if (capture) { sub = ++prog->sub; EMIT(PC++, Save); - EMIT(PC++, 2 * sub); + EMIT_CHECKED(PC++, 2 * sub); prog->len++; } else { re += 2; @@ -118,7 +126,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) if (capture) { EMIT(PC++, Save); - EMIT(PC++, 2 * sub + 1); + EMIT_CHECKED(PC++, 2 * sub + 1); prog->len++; } @@ -133,7 +141,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } else { EMIT(term, Split); } - EMIT(term + 1, REL(term, PC)); + EMIT_CHECKED(term + 1, REL(term, PC)); prog->len++; term = PC; break; @@ -141,7 +149,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) if (PC == term) return NULL; // nothing to repeat INSERT_CODE(term, 2, PC); EMIT(PC, Jmp); - EMIT(PC + 1, REL(PC, term)); + EMIT_CHECKED(PC + 1, REL(PC, term)); PC += 2; if (re[1] == '?') { EMIT(term, RSplit); @@ -149,7 +157,7 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } else { EMIT(term, Split); } - EMIT(term + 1, REL(term, PC)); + EMIT_CHECKED(term + 1, REL(term, PC)); prog->len += 2; term = PC; break; @@ -161,20 +169,20 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } else { EMIT(PC, RSplit); } - EMIT(PC + 1, REL(PC, term)); + EMIT_CHECKED(PC + 1, REL(PC, term)); PC += 2; prog->len++; term = PC; break; case '|': if (alt_label) { - EMIT(alt_label, REL(alt_label, PC) + 1); + EMIT_CHECKED(alt_label, REL(alt_label, PC) + 1); } INSERT_CODE(start, 2, PC); EMIT(PC++, Jmp); alt_label = PC++; EMIT(start, Split); - EMIT(start + 1, REL(start, PC)); + EMIT_CHECKED(start + 1, REL(start, PC)); prog->len += 2; term = PC; break; @@ -192,9 +200,9 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) } if (alt_label) { - EMIT(alt_label, REL(alt_label, PC) + 1); + EMIT_CHECKED(alt_label, REL(alt_label, PC) + 1); } - return re; + return err ? NULL : re; } int re1_5_sizecode(const char *re) diff --git a/extmod/ulab b/extmod/ulab index 743d86487c83e..ef65415b5503a 160000 --- a/extmod/ulab +++ b/extmod/ulab @@ -1 +1 @@ -Subproject commit 743d86487c83e42024ed508ed50499ad0a527d5d +Subproject commit ef65415b5503ae71cc0a9064197f2e3fa5365d74 diff --git a/extmod/uos_dupterm.c b/extmod/uos_dupterm.c index bd2dc639c81fb..4668279bc8120 100644 --- a/extmod/uos_dupterm.c +++ b/extmod/uos_dupterm.c @@ -66,7 +66,7 @@ int mp_uos_dupterm_rx_chr(void) { return buf[0]; } } else { - mp_uos_deactivate(idx, "dupterm: Exception in read() method, deactivating: ", nlr.ret_val); + mp_uos_deactivate(idx, "dupterm: Exception in read() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } @@ -84,7 +84,7 @@ void mp_uos_dupterm_tx_strn(const char *str, size_t len) { mp_stream_write(MP_STATE_VM(dupterm_objs[idx]), str, len, MP_STREAM_RW_WRITE); nlr_pop(); } else { - mp_uos_deactivate(idx, "dupterm: Exception in write() method, deactivating: ", nlr.ret_val); + mp_uos_deactivate(idx, "dupterm: Exception in write() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } } diff --git a/extmod/utime_mphal.c b/extmod/utime_mphal.c index ebbc9ac2630af..a21f2f7fc5b01 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 420f8305f742e..cac51289fda01 100644 --- a/extmod/vfs.c +++ b/extmod/vfs.c @@ -17,6 +17,10 @@ #include "extmod/vfs_fat.h" #endif +#if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX +#include "extmod/vfs_posix.h" +#endif + // For mp_vfs_proxy_call, the maximum number of additional args that can be passed. // A fixed maximum size is used to avoid the need for a costly variable array. #define PROXY_MAX_ARGS (2) @@ -75,7 +79,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 +110,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 +172,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; @@ -244,8 +248,15 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_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); + #if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX + // If the file is an integer then delegate straight to the POSIX handler + if (MP_OBJ_IS_SMALL_INT(args[ARG_file].u_obj)) { + return mp_vfs_posix_file_open(&mp_type_textio, args[ARG_file].u_obj, args[ARG_mode].u_obj); + } + #endif + 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 +325,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 85958d80d9931..c08c0912c3f0e 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 b8f43ee2959dd..5da4ecd872a91 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 432c03b7c9cf0..b3054ef2c69a6 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 ( - bdev_t pdrv, /* Physical drive nmuber (0..) */ +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 ( - bdev_t pdrv, /* Physical drive nmuber (0..) */ +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 ( - bdev_t pdrv, /* Physical drive nmuber (0..) */ +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 89786bfa361af..cbcffe11a5519 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 8d81d51751eeb..ff2ed04715e55 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,10 +168,13 @@ 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 + #ifdef DTTOIF + t->items[1] = MP_OBJ_NEW_SMALL_INT(DTTOIF(dirent->d_type)); + #else if (dirent->d_type == DT_DIR) { t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); } else if (dirent->d_type == DT_REG) { @@ -179,10 +182,12 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { } else { t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); } + #endif #else // DT_UNKNOWN should have 0 value on any reasonable system t->items[1] = MP_OBJ_NEW_SMALL_INT(0); #endif + #ifdef _DIRENT_HAVE_D_INO t->items[2] = MP_OBJ_NEW_SMALL_INT(dirent->d_ino); #else @@ -200,6 +205,9 @@ STATIC mp_obj_t vfs_posix_ilistdir(mp_obj_t self_in, mp_obj_t path_in) { iter->iternext = vfs_posix_ilistdir_it_iternext; iter->is_str = mp_obj_get_type(path_in) == &mp_type_str; const char *path = vfs_posix_get_path_str(self, path_in); + if (path[0] == '\0') { + path = "."; + } iter->dir = opendir(path); if (iter->dir == NULL) { mp_raise_OSError(errno); @@ -338,7 +346,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 593b8d6a29a52..bc45a2cf2e36d 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 a700611860abb..d9abc3c957e09 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 fb993946a2350..e19c05c8128b9 100644 --- a/extmod/virtpin.c +++ b/extmod/virtpin.c @@ -1,4 +1,4 @@ -// Copyright (c) 2016 Paul Sokolovsky +// SPDX-FileCopyrightText: Copyright (c) 2016 Paul Sokolovsky // SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) // // SPDX-License-Identifier: MIT @@ -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/frozen/Adafruit_CircuitPython_FocalTouch b/frozen/Adafruit_CircuitPython_FocalTouch index 1e3312ab1cba0..0cfa671b0c383 160000 --- a/frozen/Adafruit_CircuitPython_FocalTouch +++ b/frozen/Adafruit_CircuitPython_FocalTouch @@ -1 +1 @@ -Subproject commit 1e3312ab1cba0b1d3bb1f559c52acfdc1a6d57b8 +Subproject commit 0cfa671b0c38386ba4da59119d61d399faa9b358 diff --git a/frozen/Adafruit_CircuitPython_MIDI b/frozen/Adafruit_CircuitPython_MIDI new file mode 160000 index 0000000000000..669ab7b752d6c --- /dev/null +++ b/frozen/Adafruit_CircuitPython_MIDI @@ -0,0 +1 @@ +Subproject commit 669ab7b752d6c863577312560faf505656e5e603 diff --git a/frozen/Adafruit_CircuitPython_Register b/frozen/Adafruit_CircuitPython_Register index dd7cc167c528a..5fee6e0c38781 160000 --- a/frozen/Adafruit_CircuitPython_Register +++ b/frozen/Adafruit_CircuitPython_Register @@ -1 +1 @@ -Subproject commit dd7cc167c528a94a9feed81f9c52b5d372f68258 +Subproject commit 5fee6e0c3878110844bc51e16063eeae7d94c457 diff --git a/frozen/Adafruit_CircuitPython_SimpleMath b/frozen/Adafruit_CircuitPython_SimpleMath new file mode 160000 index 0000000000000..cdf9944730747 --- /dev/null +++ b/frozen/Adafruit_CircuitPython_SimpleMath @@ -0,0 +1 @@ +Subproject commit cdf99447307473080b2f2e95e7c3667247095ac0 diff --git a/frozen/pew-pewpew-standalone-10.x b/frozen/pew-pewpew-standalone-10.x index a14da2e1ced10..88b8be84b5dce 160000 --- a/frozen/pew-pewpew-standalone-10.x +++ b/frozen/pew-pewpew-standalone-10.x @@ -1 +1 @@ -Subproject commit a14da2e1ced1010a0da65f758199ff08eedd0bd5 +Subproject commit 88b8be84b5dce7660f58c02a63263f1d2ff0709f diff --git a/lib/libm/math.c b/lib/libm/math.c index 670d95ed2d6de..c3dbf657ff349 100644 --- a/lib/libm/math.c +++ b/lib/libm/math.c @@ -30,12 +30,17 @@ typedef float float_t; typedef union { float f; struct { - uint64_t m : 23; - uint64_t e : 8; - uint64_t s : 1; + uint32_t m : 23; + uint32_t e : 8; + uint32_t s : 1; }; } float_s_t; +int __signbitf(float f) { + float_s_t u = {.f = f}; + return u.s; +} + #ifndef NDEBUG float copysignf(float x, float y) { float_s_t fx={.f = x}; @@ -55,10 +60,14 @@ static const float _M_LN2 = 0.6931472; float log2f(float x) { return logf(x) / (float)_M_LN2; } float tanhf(float x) { - if (isinf(x)) { - return copysignf(1, x); + int sign = 0; + if (x < 0) { + sign = 1; + x = -x; } - return sinhf(x) / coshf(x); + x = expm1f(-2 * x); + x = x / (x + 2); + return sign ? x : -x; } /*****************************************************************************/ diff --git a/lib/libm/wf_tgamma.c b/lib/libm/wf_tgamma.c index 64b2488d1d3af..3ff05f331d099 100644 --- a/lib/libm/wf_tgamma.c +++ b/lib/libm/wf_tgamma.c @@ -35,6 +35,10 @@ { float y; int local_signgam; + if (!isfinite(x)) { + /* special cases: tgammaf(nan)=nan, tgammaf(inf)=inf, tgammaf(-inf)=nan */ + return x + INFINITY; + } y = expf(__ieee754_lgammaf_r(x,&local_signgam)); if (local_signgam < 0) y = -y; #ifdef _IEEE_LIBM diff --git a/lib/libm_dbl/README b/lib/libm_dbl/README index 512b3282613e4..0ef01af815c6c 100644 --- a/lib/libm_dbl/README +++ b/lib/libm_dbl/README @@ -4,6 +4,10 @@ functions. The files lgamma.c, log10.c and tanh.c are too small to have a meaningful copyright or license. +The file copysign.c contains a double version of the float copysignf provided +in libm/math.c for use in DEBUG builds where the standard library copy is +not available. + The rest of the files in this directory are copied from the musl library, v1.1.16, and, unless otherwise stated in the individual file, have the following copyright and MIT license: diff --git a/lib/libm_dbl/copysign.c b/lib/libm_dbl/copysign.c new file mode 100644 index 0000000000000..f42b09bee5aa9 --- /dev/null +++ b/lib/libm_dbl/copysign.c @@ -0,0 +1,48 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "libm.h" + +#ifndef NDEBUG +typedef union { + double d; + struct { + uint64_t m : 52; + uint64_t e : 11; + uint64_t s : 1; + }; +} double_s_t; + +double copysign(double x, double y) { + double_s_t dx={.d = x}; + double_s_t dy={.d = y}; + + // copy sign bit; + dx.s = dy.s; + + return dx.d; +} +#endif diff --git a/lib/libm_dbl/tanh.c b/lib/libm_dbl/tanh.c index 89743ba90fba9..6bdb7c39990c7 100644 --- a/lib/libm_dbl/tanh.c +++ b/lib/libm_dbl/tanh.c @@ -1,5 +1,12 @@ #include double tanh(double x) { - return sinh(x) / cosh(x); + int sign = 0; + if (x < 0) { + sign = 1; + x = -x; + } + x = expm1(-2 * x); + x = x / (x + 2); + return sign ? x : -x; } diff --git a/lib/mp3 b/lib/mp3 index bc58a654964c7..7a5de1ad777e9 160000 --- a/lib/mp3 +++ b/lib/mp3 @@ -1 +1 @@ -Subproject commit bc58a654964c799e972719a63ff12694998f3549 +Subproject commit 7a5de1ad777e95b0f4fab7bbd35678c7d319b1b5 diff --git a/lib/netutils/netutils.c b/lib/netutils/netutils.c index 4385f5a5e52eb..e82ef9270d9dc 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/protomatter b/lib/protomatter index 5e925cea7a552..98017c57349e2 160000 --- a/lib/protomatter +++ b/lib/protomatter @@ -1 +1 @@ -Subproject commit 5e925cea7a55273e375a6129761cb29b4e750d4f +Subproject commit 98017c57349e259fab70c6a7830436b19a55f6f4 diff --git a/lib/timeutils/timeutils.c b/lib/timeutils/timeutils.c index fdd3426ad4ab3..6cbea31aab8b3 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 4ba8c7fdac8cb..16861742876aa 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/tinyusb b/lib/tinyusb index 045674745afa5..ab4d30fd6bca0 160000 --- a/lib/tinyusb +++ b/lib/tinyusb @@ -1 +1 @@ -Subproject commit 045674745afa59028fbeed6dac5cb5a9c4a6033e +Subproject commit ab4d30fd6bca02c73eb9b4ff82db0b2b0f403344 diff --git a/lib/utils/buffer_helper.c b/lib/utils/buffer_helper.c index 694952e3d2cc3..a4008225d64cb 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 7487b9df533cd..9611dc309ac24 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 901c27030f7bd..261485616057c 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/mpirq.c b/lib/utils/mpirq.c new file mode 100644 index 0000000000000..dd0c220059338 --- /dev/null +++ b/lib/utils/mpirq.c @@ -0,0 +1,124 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Daniel Campora + * 2018 Tobias Badertscher + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/runtime.h" +#include "py/gc.h" +#include "lib/utils/mpirq.h" + +/****************************************************************************** + DECLARE PUBLIC DATA + ******************************************************************************/ + +const mp_arg_t mp_irq_init_args[] = { + { MP_QSTR_handler, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_none_obj)} }, + { MP_QSTR_trigger, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_hard, MP_ARG_BOOL, {.u_bool = false} }, +}; + +/****************************************************************************** + DECLARE PRIVATE DATA + ******************************************************************************/ + +/****************************************************************************** + DEFINE PUBLIC FUNCTIONS + ******************************************************************************/ + +mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent) { + mp_irq_obj_t *self = m_new0(mp_irq_obj_t, 1); + self->base.type = &mp_irq_type; + self->methods = (mp_irq_methods_t *)methods; + self->parent = parent; + self->handler = mp_const_none; + self->ishard = false; + return self; +} + +void mp_irq_handler(mp_irq_obj_t *self) { + if (self->handler != mp_const_none) { + if (self->ishard) { + // When executing code within a handler we must lock the GC to prevent + // any memory allocations. + gc_lock(); + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_call_function_1(self->handler, self->parent); + nlr_pop(); + } else { + // Uncaught exception; disable the callback so that it doesn't run again + self->methods->trigger(self->parent, 0); + self->handler = mp_const_none; + printf("Uncaught exception in IRQ callback handler\n"); + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + gc_unlock(); + } else { + // Schedule call to user function + mp_sched_schedule(self->handler, self->parent); + } + } +} + +/******************************************************************************/ +// MicroPython bindings + +STATIC mp_obj_t mp_irq_flags(mp_obj_t self_in) { + mp_irq_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_FLAGS)); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_irq_flags_obj, mp_irq_flags); + +STATIC mp_obj_t mp_irq_trigger(size_t n_args, const mp_obj_t *args) { + mp_irq_obj_t *self = MP_OBJ_TO_PTR(args[0]); + mp_obj_t ret_obj = mp_obj_new_int(self->methods->info(self->parent, MP_IRQ_INFO_TRIGGERS)); + if (n_args == 2) { + // Set trigger + self->methods->trigger(self->parent, mp_obj_get_int(args[1])); + } + return ret_obj; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_irq_trigger_obj, 1, 2, mp_irq_trigger); + +STATIC mp_obj_t mp_irq_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 0, 0, false); + mp_irq_handler(MP_OBJ_TO_PTR(self_in)); + return mp_const_none; +} + +STATIC const mp_rom_map_elem_t mp_irq_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_flags), MP_ROM_PTR(&mp_irq_flags_obj) }, + { MP_ROM_QSTR(MP_QSTR_trigger), MP_ROM_PTR(&mp_irq_trigger_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(mp_irq_locals_dict, mp_irq_locals_dict_table); + +const mp_obj_type_t mp_irq_type = { + { &mp_type_type }, + .name = MP_QSTR_irq, + .call = mp_irq_call, + .locals_dict = (mp_obj_dict_t *)&mp_irq_locals_dict, +}; diff --git a/lib/utils/mpirq.h b/lib/utils/mpirq.h new file mode 100644 index 0000000000000..548185b531147 --- /dev/null +++ b/lib/utils/mpirq.h @@ -0,0 +1,82 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Daniel Campora + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H +#define MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H + +/****************************************************************************** + DEFINE CONSTANTS + ******************************************************************************/ + +enum { + MP_IRQ_ARG_INIT_handler = 0, + MP_IRQ_ARG_INIT_trigger, + MP_IRQ_ARG_INIT_hard, + MP_IRQ_ARG_INIT_NUM_ARGS, +}; + +/****************************************************************************** + DEFINE TYPES + ******************************************************************************/ + +typedef mp_obj_t (*mp_irq_init_t)(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); +typedef mp_uint_t (*mp_irq_uint_method_one_uint_para_t)(mp_obj_t self, mp_uint_t trigger); +typedef mp_uint_t (*mp_irq_int_method_one_para_t)(mp_obj_t self, mp_uint_t info_type); + +enum { + MP_IRQ_INFO_FLAGS, + MP_IRQ_INFO_TRIGGERS, + MP_IRQ_INFO_CNT +}; + +typedef struct _mp_irq_methods_t { + mp_irq_init_t init; + mp_irq_uint_method_one_uint_para_t trigger; + mp_irq_int_method_one_para_t info; +} mp_irq_methods_t; + +typedef struct _mp_irq_obj_t { + mp_obj_base_t base; + mp_irq_methods_t *methods; + mp_obj_t parent; + mp_obj_t handler; + bool ishard; +} mp_irq_obj_t; + +/****************************************************************************** + DECLARE EXPORTED DATA + ******************************************************************************/ + +extern const mp_arg_t mp_irq_init_args[]; +extern const mp_obj_type_t mp_irq_type; + +/****************************************************************************** + DECLARE PUBLIC FUNCTIONS + ******************************************************************************/ + +mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent); +void mp_irq_handler(mp_irq_obj_t *self); + +#endif // MICROPY_INCLUDED_LIB_UTILS_MPIRQ_H diff --git a/lib/utils/printf.c b/lib/utils/printf.c index e95d778fd2cd2..dbf0c26744ea5 100644 --- a/lib/utils/printf.c +++ b/lib/utils/printf.c @@ -26,8 +26,6 @@ #include "py/mpconfig.h" -#if MICROPY_USE_INTERNAL_PRINTF - #include #include #include @@ -39,6 +37,18 @@ #include "py/formatfloat.h" #endif +#if MICROPY_DEBUG_PRINTERS +int DEBUG_printf(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + int ret = mp_vprintf(MICROPY_DEBUG_PRINTER, fmt, ap); + va_end(ap); + return ret; +} +#endif + +#if MICROPY_USE_INTERNAL_PRINTF + #undef putchar // Some stdlibs have a #define for putchar int printf(const char *fmt, ...); int vprintf(const char *fmt, va_list ap); @@ -59,20 +69,6 @@ int vprintf(const char *fmt, va_list ap) { return mp_vprintf(&mp_plat_print, fmt, ap); } -#if MICROPY_DEBUG_PRINTERS -extern const mp_print_t MICROPY_DEBUG_PRINTER_DEST; -int DEBUG_printf(const char *fmt, ...) { - va_list ap; - va_start(ap, fmt); - #ifndef MICROPY_DEBUG_PRINTER_DEST - #define MICROPY_DEBUG_PRINTER_DEST mp_plat_print - #endif - int ret = mp_vprintf(&MICROPY_DEBUG_PRINTER_DEST, fmt, ap); - va_end(ap); - return ret; -} -#endif - // need this because gcc optimises printf("%c", c) -> putchar(c), and printf("a") -> putchar('a') int putchar(int c) { char chr = c; @@ -108,7 +104,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 +130,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 68a3710ce670a..9a105a42ca556 --- 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 @@ -129,16 +129,16 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input mp_hal_stdout_tx_strn("\x04", 1); } // check for SystemExit - if (mp_obj_is_subclass_fast(mp_obj_get_type((mp_obj_t)nlr.ret_val), &mp_type_SystemExit)) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&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))) { - mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); + 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_FROM_PTR(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"); @@ -455,6 +455,12 @@ int pyexec_friendly_repl(void) { } #endif + // If the GC is locked at this point there is no way out except a reset, + // so force the GC to be unlocked to help the user debug what went wrong. + if (MP_STATE_MEM(gc_lock_depth) != 0) { + MP_STATE_MEM(gc_lock_depth) = 0; + } + vstr_reset(&line); int ret = readline(&line, ">>> "); mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT; diff --git a/lib/utils/pyexec.h b/lib/utils/pyexec.h index 4c773cd640e2a..bde2960c29b5e 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 4323e8a083bd0..500b9748beb78 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 3a11fa66c9829..c3757626c1302 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; } @@ -172,7 +172,7 @@ STATIC const mp_obj_type_t stdio_buffer_obj_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stdio_buffer_obj_stream_p, - .locals_dict = (mp_obj_t)&stdio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict, }; STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused diff --git a/locale/ID.po b/locale/ID.po index 3e0762069863f..213537ea567fb 100644 --- a/locale/ID.po +++ b/locale/ID.po @@ -6,15 +6,15 @@ msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-01-15 19:49+0000\n" -"Last-Translator: oon arfiandwi \n" +"PO-Revision-Date: 2021-04-07 12:23+0000\n" +"Last-Translator: Reza Almanda \n" "Language-Team: LANGUAGE \n" "Language: ID\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" -"X-Generator: Weblate 4.5-dev\n" +"X-Generator: Weblate 4.6-dev\n" #: main.c msgid "" @@ -29,6 +29,8 @@ msgid "" "\n" "Code stopped by auto-reload.\n" msgstr "" +"\n" +"Kode berhenti oleh auto-reload.\n" #: supervisor/shared/safe_mode.c msgid "" @@ -78,6 +80,7 @@ msgstr "%q sedang digunakan" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -107,6 +110,7 @@ msgstr "%q harus >= 1" msgid "%q must be a tuple of length 2" msgstr "%q harus berupa tuple dengan panjang 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q di luar jangkauan" @@ -337,9 +341,14 @@ msgid "All SPI peripherals are in use" msgstr "Semua perangkat SPI sedang digunakan" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Semua perangkat UART sedang digunakan" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Semua channel event sedang digunakan" @@ -368,6 +377,7 @@ msgstr "Semua timer untuk pin ini sedang digunakan" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Semua timer sedang digunakan" @@ -408,6 +418,10 @@ msgstr "AnalogOut hanya 16 bit. Nilai harus kurang dari 65536." msgid "AnalogOut not supported on given pin" msgstr "pin yang dipakai tidak mendukung AnalogOut" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -431,8 +445,8 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Mencoba alokasi heap ketika MicroPython VM tidak berjalan." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -459,6 +473,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "Di bawah frame rate minimum" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Bit clock dan word harus memiliki kesamaan pada clock unit" @@ -500,6 +518,10 @@ msgstr "Brightness tidak bisa disesuaikan" msgid "Buffer + offset too small %d %d %d" msgstr "Buffer + offset terlalu kecil %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -516,6 +538,7 @@ msgid "Buffer is too small" msgstr "Buffer terlalu kecil" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "Panjang buffer %d terlalu besar. Itu harus kurang dari %d" @@ -545,6 +568,7 @@ msgstr "Buffer terlalu pendek untuk %d byte" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Pin bus %d sudah digunakan" @@ -642,6 +666,10 @@ msgstr "" "Tidak dapat melakukan reset ke bootloader karena tidak ada bootloader yang " "terisi" +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Tidak dapat menetapkan nilai saat arah input." @@ -663,7 +691,7 @@ msgstr "Tidak dapat transfer tanpa pin MOSI dan MISO." msgid "Cannot unambiguously get sizeof scalar" msgstr "tidak dapat mendapatkan ukuran scalar secara tidak ambigu" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" "Tidak dapat membuat variasi frekuensi pada penghitung waktu yang sudah " @@ -750,14 +778,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "Tidak dapat menginisialisasi UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Tidak dapat menginisialisasi kanal" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Tidak dapat menginisialisasi timer" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Tidak dapat menginisialisasi ulang kanal" @@ -778,7 +798,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "Tidak dapat memulai PWM" @@ -834,9 +854,8 @@ msgid "Data chunk must follow fmt chunk" msgstr "Potongan data harus mengikuti fmt chunk" #: ports/nrf/common-hal/_bleio/Adapter.c -#, fuzzy msgid "Data too large for advertisement packet" -msgstr "Tidak bisa menyesuaikan data ke dalam paket advertisment" +msgstr "Data terlalu besar untuk paket advertisment" #: shared-bindings/audiobusio/PDMIn.c msgid "Destination capacity is smaller than destination_length." @@ -880,11 +899,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Channel EXTINT sedang digunakan" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Error pada regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -935,15 +959,15 @@ msgstr "Diharapkan tuple dengan panjang %d, didapatkan %d" msgid "Extended advertisements with scan response not supported." msgstr "Penyebaran yang diperluas dengan respon pindai tidak didukung." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "FFT didefinisikan hanya untuk ndarrays" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -952,11 +976,12 @@ msgid "Failed sending command." msgstr "Gagal mengirim perintah." #: ports/nrf/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Gagal untuk mendapatkan mutex, status: 0x%08lX" +msgstr "Gagal memperoleh mutex, err 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Gagal untuk mengalokasikan buffer RX" @@ -965,6 +990,7 @@ msgstr "Gagal untuk mengalokasikan buffer RX" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -978,6 +1004,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Gagal terhubung: kesalahan internal" @@ -995,14 +1025,18 @@ msgid "Failed to parse MP3 file" msgstr "Gagal mengurai file MP3" #: ports/nrf/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to release mutex, err 0x%04x" -msgstr "Gagal untuk melepaskan mutex, status: 0x%08lX" +msgstr "Gagal melepaskan mutex, err 0x%04x" #: supervisor/shared/safe_mode.c msgid "Failed to write internal flash." msgstr "Gagal menulis flash internal." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "File sudah ada" @@ -1026,7 +1060,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "Frekuensi harus cocok dengan PWMOut yang ada menggunakan timer ini" @@ -1045,10 +1079,6 @@ msgstr "" msgid "Group already used" msgstr "Grup sudah digunakan" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Grup penuh" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1079,15 +1109,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "Panjang IV harus %d byte" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1104,10 +1134,23 @@ msgstr "Ukuran penyangga salah" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1164,6 +1207,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "%q pada tidak valid" @@ -1190,8 +1234,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "Pin DAC yang diberikan tidak valid" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Frekuensi PWM tidak valid" @@ -1209,7 +1259,8 @@ msgstr "Argumen tidak valid" msgid "Invalid bits per value" msgstr "Bit per nilai tidak valid" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Ukuran buffer tidak valid" @@ -1238,14 +1289,10 @@ msgstr "File tidak valid" msgid "Invalid format chunk size" msgstr "Ukuran potongan format tidak valid" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Frekuensi yang diberikan tidak valid" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Akses memori tidak valid." @@ -1284,17 +1331,13 @@ msgstr "Pin untuk channel kanan tidak valid" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Pin-pin tidak valid" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Pin untuk PWMOut tidak valid" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1316,7 +1359,7 @@ msgstr "security_mode tidak valid" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1324,10 +1367,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "Suara tidak valid" @@ -1340,14 +1379,11 @@ msgstr "Hitungan suara tidak valid" msgid "Invalid wave file" msgstr "File wave tidak valid" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Panjang kata/bit tidak valid" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "Panjang kunci harus 16, 24, atau 32 byte" @@ -1393,14 +1429,6 @@ msgstr "Nilai x maksimum ketika dicerminkan adalah %d" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "Lompatan NLR MicroPython gagal. Kemungkinan kerusakan memori." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Kesalahan fatal MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Penundaan mulai mikrofon harus dalam kisaran 0,0 hingga 1,0" @@ -1452,6 +1480,10 @@ msgstr "Harus menyediakan pin MISO atau MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Harus menggunakan kelipatan 6 pin rgb, bukan %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1471,9 +1503,15 @@ msgstr "Tidak ada DAC (Digital Analog Converter) di dalam chip" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "tidak ada channel DMA ditemukan" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1532,6 +1570,14 @@ msgstr "Tidak ada dukungan perangkat keras pada pin clk" msgid "No hardware support on pin" msgstr "Tidak ada dukungan hardware untuk pin" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Tidak ada kunci yang ditentukan" @@ -1540,18 +1586,6 @@ msgstr "Tidak ada kunci yang ditentukan" msgid "No long integer support" msgstr "Tidak ada dukungan bilangan bulat yang panjang" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "Tidak ada lagi penghitung waktu yang tersedia pada pin ini." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "" @@ -1560,6 +1594,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "Tidak ada pull-down pada pin; 1Mohm direkomendasikan" @@ -1577,18 +1617,22 @@ msgid "No timer available" msgstr "Penghitung waktu tidak tersedia" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Pernyataan kegagalan Perangkat Lunak Nordic." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c -#, fuzzy msgid "Not connected" -msgstr "Tidak dapat menyambungkan ke AP" +msgstr "Tidak terhubung" #: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c #: shared-bindings/audiopwmio/PWMAudioOut.c @@ -1597,7 +1641,7 @@ msgstr "Tidak berfungsi" #: main.c msgid "Not running saved code.\n" -msgstr "" +msgstr "Tidak menjalankan kode yang disimpan.\n" #: shared-bindings/_bleio/__init__.c msgid "Not settable" @@ -1614,13 +1658,10 @@ msgid "Odd parity is not supported" msgstr "Parity ganjil tidak didukung" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Hanya 8 atau 16 bit mono dengan " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1674,10 +1715,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Sampel berlebihan harus kelipatan 8." @@ -1698,8 +1748,15 @@ msgstr "" "Frekuensi PWM tidak dapat ditulis ketika variabel_frequency Salah pada " "konstruksi." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBus belum didukung" @@ -1735,6 +1792,10 @@ msgstr "Pin tidak mempunya kemampuan untuk ADC (Analog Digital Converter)" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "Pin harus mendukung interupsi perangkat keras" @@ -1754,6 +1815,14 @@ msgstr "" "ideal. Jika ini tidak dapat dihindari, berikan allow_inefficient=True ke " "konstruktor" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Tambahkan module apapun pada filesystem\n" @@ -1784,6 +1853,8 @@ msgstr "Buffer awalan harus ada di heap" #: main.c msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" msgstr "" +"Tekan sembarang tombol untuk masuk ke REPL. Tekan CTRL-D untuk memuat " +"ulang.\n" #: main.c msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" @@ -1825,6 +1896,10 @@ msgstr "Kesalahan DeInit RNG" msgid "RNG Init Error" msgstr "Kesalahan Init RNG" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1832,6 +1907,7 @@ msgstr "Pembalikan RS485 ditentukan saat tidak dalam mode RS485" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "Kalibrasi RTC tidak didukung pada board ini" @@ -1840,7 +1916,7 @@ msgid "RTC is not supported on this board" msgstr "RTC tidak didukung di board ini" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS/CTS/RS485 Belum didukung pada perangkat ini" @@ -1858,9 +1934,8 @@ msgid "Read-only filesystem" msgstr "sistem file (filesystem) bersifat Read-only" #: shared-module/displayio/Bitmap.c -#, fuzzy msgid "Read-only object" -msgstr "sistem file (filesystem) bersifat Read-only" +msgstr "Objek Read-only" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Received response was invalid" @@ -1898,12 +1973,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA atau SCL membutuhkan pull up" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1939,14 +2008,6 @@ msgstr "Nilai sampel terlalu tinggi. Nilai harus kurang dari %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "Pindai sudah dalam proses. Hentikan dengan stop_scan." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "Pin CTS yang dipilih tidak valid" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "Pin RTS yang dipilih tidak valid" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1995,6 +2056,14 @@ msgstr "Memisahkan dengan menggunakan sub-captures" msgid "Stack size must be at least 256" msgstr "Ukuran stack minimal harus 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Aliran tidak menemukan metode readinto() atau write()." @@ -2086,16 +2155,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Untuk keluar, silahkan reset board tanpa " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Terlalu banyak channel dalam sampel" @@ -2108,9 +2173,8 @@ msgid "Too many displays" msgstr "Terlalu banyak tampilan" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" -"Total data yang akan ditulis lebih besar daripada outgoing_packet_length" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2136,10 +2200,6 @@ msgstr "Kesalahan Init UART" msgid "UART Re-init error" msgstr "Kesalahan Re-init UART" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "Kesalahan penulisan UART" @@ -2166,6 +2226,8 @@ msgstr "Nilai UUID bukan str, int atau byte buffer" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Tidak dapat mengalokasikan buffer untuk signed conversion" @@ -2203,7 +2265,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "Tipe urf nrfx tak sesuai" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2229,8 +2291,8 @@ msgstr "Kesalahan keamanan tidak dikenal: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Kesalahan perangkat lunak tidak dikenal: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2252,15 +2314,14 @@ msgid "Unsupported baudrate" msgstr "Baudrate tidak didukung" #: shared-module/displayio/display_core.c -#, fuzzy msgid "Unsupported display bus type" -msgstr "Baudrate tidak didukung" +msgstr "Tipe bus tampilan tidak didukung" #: shared-module/audiocore/WaveFile.c msgid "Unsupported format" msgstr "Format tidak didukung" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Operasi yang tidak didukung" @@ -2286,10 +2347,6 @@ msgstr "Panjang nilai > max_length" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Fungsi Viper saat ini tidak mendukung lebih dari 4 argumen" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Tegangan baca habis waktu" @@ -2375,11 +2432,6 @@ msgstr "sebuah objek menyerupai byte (bytes-like) dibutuhkan" msgid "abort() called" msgstr "abort() dipanggil" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "alamat %08x tidak selaras dengan %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "alamat di luar batas" @@ -2388,15 +2440,19 @@ msgstr "alamat di luar batas" msgid "addresses is empty" msgstr "alamatnya kosong" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg berisi urutan kosong" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "Argumen argsort harus berupa ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2404,10 +2460,6 @@ msgstr "" msgid "argument has wrong type" msgstr "argumen memiliki tipe yang salah" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2417,7 +2469,8 @@ msgstr "argumen num/types tidak cocok" msgid "argument should be a '%q' not a '%q'" msgstr "argumen harus berupa '%q' bukan '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "argumen harus berupa ndarrays" @@ -2430,11 +2483,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "diperlukan array/byte di sisi kanan" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "berusaha mendapatkan argmin/argmax dari urutan kosong" @@ -2442,15 +2495,15 @@ msgstr "berusaha mendapatkan argmin/argmax dari urutan kosong" msgid "attributes not supported yet" msgstr "atribut belum didukung" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2475,7 +2528,7 @@ msgid "binary op %q not implemented" msgstr "" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" +msgid "bits must be in range 5 to 9" msgstr "" #: shared-bindings/audiomixer/Mixer.c @@ -2486,22 +2539,17 @@ msgstr "" msgid "branch not in range" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" #: shared-module/struct/__init__.c -#, fuzzy msgid "buffer size must match format" -msgstr "buffers harus mempunyai panjang yang sama" +msgstr "ukuran buffer harus sesuai dengan format" #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c msgid "buffer slices must be of equal length" @@ -2512,7 +2560,7 @@ msgstr "" msgid "buffer too small" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2578,6 +2626,10 @@ msgstr "tidak dapat menetapkan ke ekspresi" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2586,6 +2638,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2704,6 +2760,10 @@ msgstr "" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2748,19 +2808,19 @@ msgstr "" msgid "conversion to object" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2768,15 +2828,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2813,14 +2873,18 @@ msgstr "" msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2928,7 +2992,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2936,11 +3000,11 @@ msgstr "" msgid "filesystem must provide mount method" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2948,11 +3012,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2964,7 +3024,7 @@ msgstr "" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2985,8 +3045,8 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "fungsi tidak dapat mengambil argumen keyword" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -2997,7 +3057,7 @@ msgstr "fungsi diharapkan setidaknya %d argumen, hanya mendapatkan %d" msgid "function got multiple values for argument '%q'" msgstr "fungsi mendapatkan nilai ganda untuk argumen '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -3040,6 +3100,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3072,8 +3136,9 @@ msgstr "lapisan (padding) tidak benar" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "index keluar dari jangkauan" @@ -3085,7 +3150,7 @@ msgstr "" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3105,7 +3170,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3113,15 +3178,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3137,23 +3202,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3165,7 +3230,7 @@ msgstr "" msgid "integer required" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3178,14 +3243,33 @@ msgstr "" msgid "invalid arguments" msgstr "argumen-argumen tidak valid" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "cert tidak valid" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "indeks dupterm tidak valid" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "format tidak valid" @@ -3227,10 +3311,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3239,11 +3319,7 @@ msgstr "" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3311,11 +3387,7 @@ msgstr "" msgid "math domain error" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3337,15 +3409,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3358,11 +3430,15 @@ msgstr "" msgid "memory allocation failed, heap is locked" msgstr "" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "modul tidak ditemukan" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3407,6 +3483,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3480,10 +3560,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3552,7 +3628,7 @@ msgstr "" msgid "odd-length string" msgstr "panjang data string memiliki keganjilan (odd-length)" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3582,8 +3658,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3591,7 +3667,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3608,11 +3684,19 @@ msgstr "" msgid "ord() expected a character, but string of length %d found" msgstr "" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3633,10 +3717,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "anotasi parameter haruse sebuah identifier" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3645,7 +3725,7 @@ msgstr "" msgid "parameters must be registers in sequence r0 to r3" msgstr "parameter harus menjadi register dalam urutan r0 sampai r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "" @@ -3668,11 +3748,16 @@ msgstr "Muncul dari PulseIn yang kosong" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "" @@ -3683,12 +3768,17 @@ msgstr "" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3696,6 +3786,7 @@ msgstr "" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3707,6 +3798,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3723,7 +3822,7 @@ msgstr "antrian meluap (overflow)" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3758,7 +3857,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3773,6 +3872,7 @@ msgid "" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "nilai sampling keluar dari jangkauan" @@ -3804,7 +3904,7 @@ msgstr "" msgid "single '}' encountered in format string" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3828,23 +3928,23 @@ msgstr "" msgid "soft reboot\n" msgstr "memulai ulang software(soft reboot)\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3931,9 +4031,8 @@ msgid "timeout must be < 655.35 secs" msgstr "" #: shared-bindings/_bleio/CharacteristicBuffer.c -#, fuzzy msgid "timeout must be >= 0.0" -msgstr "bits harus memilki nilai 8" +msgstr "waktu habis harus >= 0,0" #: shared-module/sdcardio/SDCard.c msgid "timeout waiting for v1 card" @@ -3955,7 +4054,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3968,18 +4067,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4061,7 +4156,7 @@ msgstr "" msgid "unknown type" msgstr "tipe tidak diketahui" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4114,14 +4209,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4130,6 +4217,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4142,21 +4234,22 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" -msgstr "" +msgstr "indeks sumbu salah" #: extmod/ulab/code/ulab_create.c msgid "wrong axis specified" -msgstr "" +msgstr "sumbu yang ditentukan salah" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" -msgstr "" +msgstr "tipe input salah" #: extmod/ulab/code/ulab_create.c py/objstr.c msgid "wrong number of arguments" -msgstr "" +msgstr "jumlah argumen salah" #: py/runtime.c msgid "wrong number of values to unpack" @@ -4166,7 +4259,7 @@ msgstr "" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4190,18 +4283,76 @@ msgstr "" msgid "zero step" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" -msgstr "" +msgstr "zi harus ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" -msgstr "" +msgstr "zi harus berjenis float" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Fungsi Viper saat ini tidak mendukung lebih dari 4 argumen" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "alamat %08x tidak selaras dengan %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "fungsi tidak dapat mengambil argumen keyword" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "anotasi parameter haruse sebuah identifier" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Total data yang akan ditulis lebih besar daripada outgoing_packet_length" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Mencoba alokasi heap ketika MicroPython VM tidak berjalan." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "Lompatan NLR MicroPython gagal. Kemungkinan kerusakan memori." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Kesalahan fatal MicroPython." + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Pernyataan kegagalan Perangkat Lunak Nordic." + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Kesalahan perangkat lunak tidak dikenal: %04x" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Pin CTS yang dipilih tidak valid" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Pin RTS yang dipilih tidak valid" + +#~ msgid "Could not initialize channel" +#~ msgstr "Tidak dapat menginisialisasi kanal" + +#~ msgid "Could not initialize timer" +#~ msgstr "Tidak dapat menginisialisasi timer" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Frekuensi yang diberikan tidak valid" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Pin untuk PWMOut tidak valid" + +#~ msgid "No more timers available on this pin." +#~ msgstr "Tidak ada lagi penghitung waktu yang tersedia pada pin ini." + +#~ msgid "Group full" +#~ msgstr "Grup penuh" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA atau SCL membutuhkan pull up" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "pin alamat %d dan pin rgb %d menunjukkan tinggi %d, bukan %d" diff --git a/locale/circuitpython.pot b/locale/circuitpython.pot index 0fd758e978ca8..c1f8074e614cc 100644 --- a/locale/circuitpython.pot +++ b/locale/circuitpython.pot @@ -73,6 +73,7 @@ msgstr "" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -102,6 +103,7 @@ msgstr "" msgid "%q must be a tuple of length 2" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "" @@ -332,9 +334,14 @@ msgid "All SPI peripherals are in use" msgstr "" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "" @@ -363,6 +370,7 @@ msgstr "" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "" @@ -403,6 +411,10 @@ msgstr "" msgid "AnalogOut not supported on given pin" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -426,7 +438,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -452,6 +464,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "" @@ -493,6 +509,10 @@ msgstr "" msgid "Buffer + offset too small %d %d %d" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -509,6 +529,7 @@ msgid "Buffer is too small" msgstr "" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "" @@ -538,6 +559,7 @@ msgstr "" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "" @@ -629,6 +651,10 @@ msgstr "" msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "" @@ -650,7 +676,7 @@ msgstr "" msgid "Cannot unambiguously get sizeof scalar" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" @@ -732,14 +758,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "" @@ -760,7 +778,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "" @@ -861,11 +879,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -916,15 +939,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -938,6 +961,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "" @@ -946,6 +970,7 @@ msgstr "" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -959,6 +984,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "" @@ -984,6 +1013,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1007,7 +1040,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1026,10 +1059,6 @@ msgstr "" msgid "Group already used" msgstr "" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1060,15 +1089,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1083,10 +1112,23 @@ msgstr "" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1143,6 +1185,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "" @@ -1169,8 +1213,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "" @@ -1188,7 +1238,8 @@ msgstr "" msgid "Invalid bits per value" msgstr "" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "" @@ -1205,6 +1256,11 @@ msgstr "" msgid "Invalid channel count" msgstr "" +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_count %d" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Invalid direction." msgstr "" @@ -1217,14 +1273,10 @@ msgstr "" msgid "Invalid format chunk size" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "" @@ -1263,17 +1315,13 @@ msgstr "" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1295,7 +1343,7 @@ msgstr "" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1303,10 +1351,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1319,14 +1363,11 @@ msgstr "" msgid "Invalid wave file" msgstr "" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "" @@ -1372,14 +1413,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1431,6 +1464,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1450,9 +1487,15 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1511,24 +1554,20 @@ msgstr "" msgid "No hardware support on pin" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "No key was specified" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" +#: shared-bindings/aesio/aes.c +msgid "No key was specified" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." +#: shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" #: shared-bindings/wifi/Radio.c @@ -1539,6 +1578,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1556,13 +1601,18 @@ msgid "No timer available" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1591,13 +1641,10 @@ msgid "Odd parity is not supported" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1647,10 +1694,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "" @@ -1669,8 +1725,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "" @@ -1706,6 +1769,10 @@ msgstr "" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "" @@ -1722,6 +1789,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "" @@ -1793,7 +1868,7 @@ msgstr "" msgid "RNG Init Error" msgstr "" -#: ports/nrf/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c msgid "RS485 Not yet supported on this device" msgstr "" @@ -1870,12 +1945,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1911,14 +1980,6 @@ msgstr "" msgid "Scan already in progess. Stop with stop_scan." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1967,6 +2028,14 @@ msgstr "" msgid "Stack size must be at least 256" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "" @@ -2051,9 +2120,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +msgid "Timeout waiting for DRDY" +msgstr "" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +msgid "Timeout waiting for VSYNC" msgstr "" #: supervisor/shared/safe_mode.c @@ -2061,6 +2133,7 @@ msgid "To exit, please reset the board without " msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "" @@ -2073,7 +2146,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2100,10 +2173,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "" @@ -2130,6 +2199,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "" @@ -2167,7 +2238,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2193,7 +2264,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2221,7 +2292,7 @@ msgstr "" msgid "Unsupported format" msgstr "" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "" @@ -2247,10 +2318,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2330,11 +2397,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2343,15 +2405,19 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2359,10 +2425,6 @@ msgstr "" msgid "argument has wrong type" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2372,7 +2434,8 @@ msgstr "" msgid "argument should be a '%q' not a '%q'" msgstr "" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2385,11 +2448,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2397,15 +2460,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2430,7 +2493,7 @@ msgid "binary op %q not implemented" msgstr "" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" +msgid "bits must be in range 5 to 9" msgstr "" #: shared-bindings/audiomixer/Mixer.c @@ -2441,15 +2504,11 @@ msgstr "" msgid "branch not in range" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2466,7 +2525,7 @@ msgstr "" msgid "buffer too small" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2532,6 +2591,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2540,6 +2603,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2658,6 +2725,10 @@ msgstr "" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2702,19 +2773,19 @@ msgstr "" msgid "conversion to object" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2722,18 +2793,23 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "" + #: extmod/ulab/code/ndarray.c msgid "data type not understood" msgstr "" @@ -2767,14 +2843,18 @@ msgstr "" msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2882,7 +2962,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2890,11 +2970,11 @@ msgstr "" msgid "filesystem must provide mount method" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2902,11 +2982,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2918,7 +2994,7 @@ msgstr "" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2939,7 +3015,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -2951,7 +3027,7 @@ msgstr "" msgid "function got multiple values for argument '%q'" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -2994,6 +3070,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3026,8 +3106,9 @@ msgstr "" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "" @@ -3039,7 +3120,7 @@ msgstr "" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3059,7 +3140,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3067,15 +3148,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3091,23 +3172,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3119,7 +3200,7 @@ msgstr "" msgid "integer required" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3132,14 +3213,33 @@ msgstr "" msgid "invalid arguments" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "" @@ -3181,10 +3281,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3193,11 +3289,7 @@ msgstr "" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3265,11 +3357,7 @@ msgstr "" msgid "math domain error" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3291,15 +3379,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3312,11 +3400,15 @@ msgstr "" msgid "memory allocation failed, heap is locked" msgstr "" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3361,6 +3453,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3434,10 +3530,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3506,7 +3598,7 @@ msgstr "" msgid "odd-length string" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3535,8 +3627,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3544,7 +3636,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3561,11 +3653,19 @@ msgstr "" msgid "ord() expected a character, but string of length %d found" msgstr "" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3586,10 +3686,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3598,7 +3694,7 @@ msgstr "" msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "" @@ -3621,11 +3717,16 @@ msgstr "" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "" @@ -3636,12 +3737,17 @@ msgstr "" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3649,6 +3755,7 @@ msgstr "" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3660,6 +3767,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3676,7 +3791,7 @@ msgstr "" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3711,7 +3826,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3726,6 +3841,7 @@ msgid "" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "" @@ -3757,7 +3873,7 @@ msgstr "" msgid "single '}' encountered in format string" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3781,23 +3897,23 @@ msgstr "" msgid "soft reboot\n" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3907,7 +4023,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3920,18 +4036,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4013,7 +4125,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4066,14 +4178,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4082,6 +4186,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4094,7 +4203,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4102,7 +4211,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4118,7 +4228,7 @@ msgstr "" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4142,14 +4252,14 @@ msgstr "" msgid "zero step" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" diff --git a/locale/cs.po b/locale/cs.po index e6ad0a83f7c9b..874f0bf329c79 100644 --- a/locale/cs.po +++ b/locale/cs.po @@ -76,6 +76,7 @@ msgstr "Používá se %q" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -105,6 +106,7 @@ msgstr "%q musí být > = 1" msgid "%q must be a tuple of length 2" msgstr "%q musí být n-tice délky 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q je mimo rozsah" @@ -335,9 +337,14 @@ msgid "All SPI peripherals are in use" msgstr "" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "" @@ -366,6 +373,7 @@ msgstr "" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "" @@ -406,6 +414,10 @@ msgstr "" msgid "AnalogOut not supported on given pin" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -429,7 +441,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -455,6 +467,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "" @@ -496,6 +512,10 @@ msgstr "" msgid "Buffer + offset too small %d %d %d" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -512,6 +532,7 @@ msgid "Buffer is too small" msgstr "" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "" @@ -541,6 +562,7 @@ msgstr "" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "" @@ -632,6 +654,10 @@ msgstr "" msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "" @@ -653,7 +679,7 @@ msgstr "" msgid "Cannot unambiguously get sizeof scalar" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" @@ -735,14 +761,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "" @@ -763,7 +781,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "" @@ -864,11 +882,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -919,15 +942,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -941,6 +964,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "" @@ -949,6 +973,7 @@ msgstr "" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -962,6 +987,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "" @@ -987,6 +1016,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1010,7 +1043,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1029,10 +1062,6 @@ msgstr "" msgid "Group already used" msgstr "" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1063,15 +1092,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1086,10 +1115,23 @@ msgstr "" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1146,6 +1188,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "" @@ -1172,8 +1215,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "" @@ -1191,7 +1240,8 @@ msgstr "" msgid "Invalid bits per value" msgstr "" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "" @@ -1220,14 +1270,10 @@ msgstr "" msgid "Invalid format chunk size" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "" @@ -1266,17 +1312,13 @@ msgstr "" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1298,7 +1340,7 @@ msgstr "" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1306,10 +1348,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1322,14 +1360,11 @@ msgstr "" msgid "Invalid wave file" msgstr "" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "" @@ -1375,14 +1410,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1434,6 +1461,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1453,9 +1484,15 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1514,24 +1551,20 @@ msgstr "" msgid "No hardware support on pin" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "No key was specified" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" +#: shared-bindings/aesio/aes.c +msgid "No key was specified" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." +#: shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" #: shared-bindings/wifi/Radio.c @@ -1542,6 +1575,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1559,13 +1598,18 @@ msgid "No timer available" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1594,13 +1638,10 @@ msgid "Odd parity is not supported" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1650,10 +1691,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "" @@ -1672,8 +1722,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "" @@ -1709,6 +1766,10 @@ msgstr "" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "" @@ -1725,6 +1786,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "" @@ -1796,6 +1865,10 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1803,6 +1876,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "" @@ -1811,7 +1885,7 @@ msgid "RTC is not supported on this board" msgstr "" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "" @@ -1868,12 +1942,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1909,14 +1977,6 @@ msgstr "" msgid "Scan already in progess. Stop with stop_scan." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1965,6 +2025,14 @@ msgstr "" msgid "Stack size must be at least 256" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "" @@ -2049,16 +2117,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "" @@ -2071,7 +2135,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2098,10 +2162,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "" @@ -2128,6 +2188,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "" @@ -2165,7 +2227,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2191,7 +2253,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2219,7 +2281,7 @@ msgstr "" msgid "Unsupported format" msgstr "" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "" @@ -2245,10 +2307,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2328,11 +2386,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2341,15 +2394,19 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2357,10 +2414,6 @@ msgstr "" msgid "argument has wrong type" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2370,7 +2423,8 @@ msgstr "" msgid "argument should be a '%q' not a '%q'" msgstr "" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2383,11 +2437,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2395,15 +2449,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2428,7 +2482,7 @@ msgid "binary op %q not implemented" msgstr "" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" +msgid "bits must be in range 5 to 9" msgstr "" #: shared-bindings/audiomixer/Mixer.c @@ -2439,15 +2493,11 @@ msgstr "" msgid "branch not in range" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2464,7 +2514,7 @@ msgstr "" msgid "buffer too small" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2530,6 +2580,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2538,6 +2592,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2656,6 +2714,10 @@ msgstr "" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2700,19 +2762,19 @@ msgstr "" msgid "conversion to object" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2720,15 +2782,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2765,14 +2827,18 @@ msgstr "" msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2880,7 +2946,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2888,11 +2954,11 @@ msgstr "" msgid "filesystem must provide mount method" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2900,11 +2966,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2916,7 +2978,7 @@ msgstr "" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2937,7 +2999,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -2949,7 +3011,7 @@ msgstr "" msgid "function got multiple values for argument '%q'" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -2992,6 +3054,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3024,8 +3090,9 @@ msgstr "" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "" @@ -3037,7 +3104,7 @@ msgstr "" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3057,7 +3124,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3065,15 +3132,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3089,23 +3156,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3117,7 +3184,7 @@ msgstr "" msgid "integer required" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3130,14 +3197,33 @@ msgstr "" msgid "invalid arguments" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "" @@ -3179,10 +3265,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3191,11 +3273,7 @@ msgstr "" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3263,11 +3341,7 @@ msgstr "" msgid "math domain error" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3289,15 +3363,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3310,11 +3384,15 @@ msgstr "" msgid "memory allocation failed, heap is locked" msgstr "" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3359,6 +3437,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3432,10 +3514,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3504,7 +3582,7 @@ msgstr "" msgid "odd-length string" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3533,8 +3611,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3542,7 +3620,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3559,11 +3637,19 @@ msgstr "" msgid "ord() expected a character, but string of length %d found" msgstr "" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3584,10 +3670,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3596,7 +3678,7 @@ msgstr "" msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "" @@ -3619,11 +3701,16 @@ msgstr "" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "" @@ -3634,12 +3721,17 @@ msgstr "" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3647,6 +3739,7 @@ msgstr "" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3658,6 +3751,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3674,7 +3775,7 @@ msgstr "" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3709,7 +3810,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3724,6 +3825,7 @@ msgid "" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "" @@ -3755,7 +3857,7 @@ msgstr "" msgid "single '}' encountered in format string" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3779,23 +3881,23 @@ msgstr "" msgid "soft reboot\n" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3905,7 +4007,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3918,18 +4020,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4011,7 +4109,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4064,14 +4162,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4080,6 +4170,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4092,7 +4187,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4100,7 +4195,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4116,7 +4212,7 @@ msgstr "" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4140,15 +4236,15 @@ msgstr "" msgid "zero step" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" diff --git a/locale/de_DE.po b/locale/de_DE.po index e23f27bfe3e98..d59651ef3e43c 100644 --- a/locale/de_DE.po +++ b/locale/de_DE.po @@ -6,14 +6,14 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-01-07 18:01+0000\n" -"Last-Translator: Dennis Schweer \n" +"PO-Revision-Date: 2021-03-16 00:47+0000\n" +"Last-Translator: Daniel Glocker \n" "Language: de_DE\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" -"X-Generator: Weblate 4.4.1-dev\n" +"X-Generator: Weblate 4.5.2-dev\n" #: main.c msgid "" @@ -28,6 +28,8 @@ msgid "" "\n" "Code stopped by auto-reload.\n" msgstr "" +"\n" +"Code durch automatisches neuladen gestoppt\n" #: supervisor/shared/safe_mode.c msgid "" @@ -49,7 +51,7 @@ msgstr " Datei \"%q\", Zeile %d" #: py/builtinhelp.c msgid " is of type %q\n" -msgstr "" +msgstr " ist vom Type %q\n" #: main.c msgid " output:\n" @@ -65,6 +67,8 @@ msgstr "%%c erwartet int oder char" msgid "" "%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" msgstr "" +"%d Address Pins, %d rgb Pins und %d Tiles indiziert eine Höhe von %d, nicht " +"%d" #: ports/atmel-samd/common-hal/sdioio/SDCard.c msgid "%q failure: %d" @@ -77,6 +81,7 @@ msgstr "%q in Benutzung" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -106,6 +111,7 @@ msgstr "%q muss >= 1 sein" msgid "%q must be a tuple of length 2" msgstr "%q muss ein Tupel der Länge 2 sein" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q außerhalb des Bereichs" @@ -120,12 +126,13 @@ msgstr "%q sollte ein integer sein" #: py/bc.c py/objnamedtuple.c msgid "%q() takes %d positional arguments but %d were given" -msgstr "%q() nimmt %d Argumente ohne Keyword an, aber es wurden %d angegeben" +msgstr "" +"%q() nimmt %d Argumente ohne Schlüsselwort an, aber es wurden %d angegeben" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c #, c-format msgid "%s error 0x%x" -msgstr "" +msgstr "%s Error 0x%x" #: py/argcheck.c msgid "'%q' argument required" @@ -145,7 +152,7 @@ msgstr "'%q' Objekt unterschützt keine Elementzuweisung" #: py/obj.c msgid "'%q' object does not support item deletion" -msgstr "'%q' objekt unterstützt das " +msgstr "'%q' Objekt unterstützt löschen von Elementen nicht" #: py/runtime.c msgid "'%q' object has no attribute '%q'" @@ -161,7 +168,7 @@ msgstr "'%q' Objekt ist kein callable" #: py/runtime.c msgid "'%q' object is not iterable" -msgstr "" +msgstr "'%q' Objekt ist nicht iterierbar" #: py/obj.c msgid "'%q' object is not subscriptable" @@ -235,7 +242,7 @@ msgstr "'await' außerhalb einer Funktion" #: py/compile.c msgid "'await', 'async for' or 'async with' outside async function" -msgstr "" +msgstr "'await', 'async for' oder 'async with' außerhalb einer async Funktion" #: py/compile.c msgid "'break' outside loop" @@ -267,7 +274,7 @@ msgstr "'return' außerhalb einer Funktion" #: py/compile.c msgid "'yield from' inside async function" -msgstr "" +msgstr "'yield from' innerhalb einer async Funktion" #: py/compile.c msgid "'yield' outside function" @@ -291,7 +298,7 @@ msgstr "3-arg pow() wird nicht unterstützt" #: shared-module/msgpack/__init__.c msgid "64 bit types" -msgstr "" +msgstr "64 bit Typen" #: ports/atmel-samd/common-hal/countio/Counter.c #: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c @@ -313,7 +320,7 @@ msgstr "Adresstyp außerhalb des zulässigen Bereichs" #: ports/esp32s2/common-hal/canio/CAN.c msgid "All CAN peripherals are in use" -msgstr "" +msgstr "Alle CAN Schnittstellen sind in Benutzung" #: ports/esp32s2/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c msgid "All I2C peripherals are in use" @@ -329,23 +336,28 @@ msgstr "Alle PCNT Einheiten sind in Benutzung" #: ports/esp32s2/common-hal/canio/Listener.c #: ports/stm/common-hal/canio/Listener.c msgid "All RX FIFOs in use" -msgstr "" +msgstr "Alle RX FIFOs sind in Benutzung" #: ports/esp32s2/common-hal/busio/SPI.c ports/nrf/common-hal/busio/SPI.c msgid "All SPI peripherals are in use" msgstr "Alle SPI-Peripheriegeräte sind in Benutzung" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Alle UART-Peripheriegeräte sind in Benutzung" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Alle event Kanäle werden benutzt" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "All state machines in use" -msgstr "" +msgstr "Alle state machines in verwendung" #: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "All sync event channels in use" @@ -367,6 +379,7 @@ msgstr "Alle timer für diesen Pin werden bereits benutzt" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Alle timer werden benutzt" @@ -407,6 +420,10 @@ msgstr "AnalogOut kann nur 16 Bit. Der Wert muss unter 65536 liegen." msgid "AnalogOut not supported on given pin" msgstr "AnalogOut ist an diesem Pin nicht unterstützt" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -430,10 +447,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Versuche %d Blöcke zu allokieren" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" -"Versuch einer Heap Reservierung, wenn die MicroPython-VM nicht ausgeführt " -"wird." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -453,13 +468,17 @@ msgstr "" #: ports/esp32s2/common-hal/canio/CAN.c msgid "Baudrate not supported by peripheral" -msgstr "" +msgstr "Baudrate wird von der Peripherie nicht unterstützt" #: shared-module/displayio/Display.c #: shared-module/framebufferio/FramebufferDisplay.c msgid "Below minimum frame rate" msgstr "Unterhalb der minimalen Frame Rate" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Bit clock und word select müssen eine clock unit teilen" @@ -467,7 +486,7 @@ msgstr "Bit clock und word select müssen eine clock unit teilen" #: shared-bindings/rgbmatrix/RGBMatrix.c #, c-format msgid "Bit depth must be from 1 to 6 inclusive, not %d" -msgstr "" +msgstr "Bittiefe muss zwischen 1 und 6 liegen, nicht %d" #: shared-bindings/audiobusio/PDMIn.c msgid "Bit depth must be multiple of 8." @@ -501,6 +520,10 @@ msgstr "Die Helligkeit ist nicht einstellbar" msgid "Buffer + offset too small %d %d %d" msgstr "Buffer + Offset zu klein %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -517,6 +540,7 @@ msgid "Buffer is too small" msgstr "Der Puffer ist zu klein" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "Die Pufferlänge %d ist zu groß. Sie muss kleiner als %d sein" @@ -541,11 +565,12 @@ msgstr "Puffer zu groß und kann nicht reserviert werden" #: shared-bindings/_bleio/PacketBuffer.c #, c-format msgid "Buffer too short by %d bytes" -msgstr "Buffer um %d Bytes zu kurz" +msgstr "Puffer um %d Bytes zu kurz" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Bus pin %d wird schon benutzt" @@ -564,7 +589,7 @@ msgstr "CBC-Blöcke müssen ein Vielfaches von 16 Bytes sein" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "CRC or checksum was invalid" -msgstr "" +msgstr "CRC oder Checksumme ungültig" #: py/objtype.c msgid "Call super().__init__() before accessing native object." @@ -572,7 +597,7 @@ msgstr "Rufe super().__init__() vor dem Zugriff auf ein natives Objekt auf." #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Can only alarm on RTC IO from deep sleep." -msgstr "" +msgstr "Alarm der RTC IO kann nur im deep sleep ausgeführt werden." #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Can only alarm on one low pin while others alarm high from deep sleep." @@ -618,7 +643,7 @@ msgstr "Kann nicht beite Kanäle auf dem gleichen Pin ausgeben" #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Cannot pull on input-only pin." -msgstr "" +msgstr "Kann nicht 'pull' an einem 'input-only' pin." #: shared-module/bitbangio/SPI.c msgid "Cannot read without MISO pin." @@ -638,6 +663,10 @@ msgstr "Kann '/' nicht remounten when USB aktiv ist." msgid "Cannot reset into bootloader because no bootloader is present." msgstr "Reset zum bootloader nicht möglich da bootloader nicht vorhanden." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "Socket Optionen können nicht gesetzt werden" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Der Wert kann nicht gesetzt werden, wenn die Richtung input ist." @@ -659,14 +688,14 @@ msgstr "Übertragung ohne MOSI- und MISO-Pins nicht möglich." msgid "Cannot unambiguously get sizeof scalar" msgstr "sizeof scalar kann nicht eindeutig bestimmt werden" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" "Die Frequenz eines bereits verwendeten Timers kann nicht variiert werden" #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Cannot wake on pin edge. Only level." -msgstr "" +msgstr "Kann nicht auf Flanke wecken, nur auf Level." #: shared-module/bitbangio/SPI.c msgid "Cannot write without MOSI pin." @@ -691,7 +720,7 @@ msgstr "" #: supervisor/shared/safe_mode.c msgid "CircuitPython was unable to allocate the heap.\n" -msgstr "" +msgstr "CircuitPython war es nicht möglich heap-Speicher zu allozieren.\n" #: shared-module/bitbangio/SPI.c msgid "Clock pin init failed." @@ -747,14 +776,6 @@ msgstr "Konnte SDKarte nicht initialisieren" msgid "Could not initialize UART" msgstr "Konnte UART nicht initialisieren" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Kanal konnte nicht initialisiert werden" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Timer konnte nicht initialisiert werden" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Kanal konnte nicht neu initiiert werden" @@ -769,13 +790,13 @@ msgstr "PWM konnte nicht neu gestartet werden" #: ports/esp32s2/common-hal/neopixel_write/__init__.c msgid "Could not retrieve clock" -msgstr "" +msgstr "Clock konnte nicht ermittelt werden" #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Konnte Adresse nicht setzen" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "PWM konnte nicht gestartet werden" @@ -807,7 +828,7 @@ msgstr "Absturz in den HardFault_Handler." #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" -msgstr "DAC Kanal Intialisierungs Fehler" +msgstr "DAC Kanal Initialisierungsfehler" #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Device Init Error" @@ -824,7 +845,7 @@ msgstr "Data 0 pin muss am Byte ausgerichtet sein" #: ports/esp32s2/common-hal/displayio/ParallelBus.c msgid "Data 0 pin must be byte aligned." -msgstr "" +msgstr "Data 0 Pin muss Byte aligned sein." #: shared-module/audiocore/WaveFile.c msgid "Data chunk must follow fmt chunk" @@ -876,13 +897,18 @@ msgstr "ESP-IDF Speicherallozierung fehlgeschlagen" msgid "EXTINT channel already in use" msgstr "EXTINT Kanal ist schon in Benutzung" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Fehler in regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" -msgstr "" +msgstr "Error: Bind Fehler" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c py/enum.c #: shared-bindings/_bleio/__init__.c shared-bindings/aesio/aes.c @@ -920,7 +946,7 @@ msgstr "Erwartet eine Adresse" #: shared-bindings/alarm/__init__.c msgid "Expected an alarm" -msgstr "" +msgstr "Alarm erwartet" #: shared-module/_pixelbuf/PixelBuf.c #, c-format @@ -932,15 +958,15 @@ msgid "Extended advertisements with scan response not supported." msgstr "" "Erweiterte Werbung (advertising) mit Scanantwort wird nicht unterstützt." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "FFT ist nur für ndarrays definiert" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "FFT ist nur für lineare Arrays implementiert" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "SSL Handshake fehlgeschlagen" @@ -954,6 +980,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Mutex konnte nicht akquiriert werden. Status: 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Konnte keinen RX Buffer allozieren" @@ -962,6 +989,7 @@ msgstr "Konnte keinen RX Buffer allozieren" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -973,6 +1001,10 @@ msgstr "Zuweisung des Wifi Speichers ist fehlgeschlagen" #: ports/esp32s2/common-hal/wifi/ScannedNetworks.c msgid "Failed to allocate wifi scan memory" +msgstr "Zuweisung des Wifi Scan Speichers ist fehlgeschlagen" + +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" msgstr "" #: ports/nrf/common-hal/_bleio/Adapter.c @@ -989,7 +1021,7 @@ msgstr "Wifi Initialisierung ist fehlgeschlagen" #: shared-module/audiomp3/MP3Decoder.c msgid "Failed to parse MP3 file" -msgstr "Parsen der MP3 Datei fehlgeschlagen" +msgstr "MP3-Datei konnte nicht analysiert werden" #: ports/nrf/sd_mutex.c #, c-format @@ -1000,6 +1032,10 @@ msgstr "Mutex konnte nicht freigegeben werden. Status: 0x%04x" msgid "Failed to write internal flash." msgstr "Interner Flash konnte nicht geschrieben werden." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Datei existiert" @@ -1012,7 +1048,7 @@ msgstr "Filter zu komplex" #: ports/esp32s2/common-hal/dualbank/__init__.c msgid "Firmware image is invalid" -msgstr "" +msgstr "Firmware Image ist ungültig" #: ports/cxd56/common-hal/camera/Camera.c msgid "Format not supported" @@ -1023,7 +1059,7 @@ msgstr "Format nicht unterstützt" msgid "Framebuffer requires %d bytes" msgstr "Framepuffer benötigt %d bytes" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" "Die Frequenz muss mit dem vorhandenen PWMOut unter Verwendung dieses Timers " @@ -1036,7 +1072,7 @@ msgstr "Die Funktion erwartet, dass der 'lock'-Befehl zuvor ausgeführt wurde" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Generic Failure" -msgstr "" +msgstr "Generischer Fehler" #: shared-bindings/displayio/Display.c #: shared-bindings/displayio/EPaperDisplay.c @@ -1044,10 +1080,6 @@ msgstr "" msgid "Group already used" msgstr "Gruppe schon benutzt" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Gruppe voll" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1072,21 +1104,21 @@ msgstr "I2C-Init-Fehler" #: ports/raspberrypi/common-hal/busio/I2C.c msgid "I2C peripheral in use" -msgstr "" +msgstr "I2C Peripherie in Verwendung" #: shared-bindings/audiobusio/I2SOut.c msgid "I2SOut not available" msgstr "I2SOut nicht verfügbar" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 & 4 unterstützen keinen internen Pull up im sleep-Modus" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IV muss %d Bytes lang sein" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1101,15 +1133,28 @@ msgstr "Inkorrekte Puffergröße" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Init program size invalid" +msgstr "Init Programm Größe ungültig" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" msgstr "" #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "Initialisierung aufgrund von Speichermangel fehlgeschlagen" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "Input buffer länge (%d) muss ein vielfaches vom Strand Count (%d) sein" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" -msgstr "" +msgstr "Input benötigt zu lange" #: ports/esp32s2/common-hal/neopixel_write/__init__.c py/moduerrno.c msgid "Input/output error" @@ -1118,7 +1163,7 @@ msgstr "Eingabe-/Ausgabefehler" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d jumps on pin" -msgstr "" +msgstr "Instruktion %d springt auf Pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format @@ -1163,6 +1208,7 @@ msgstr "Ungültiger %q" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Ungültiger %q Pin" @@ -1189,15 +1235,21 @@ msgstr "Ungültige BSSID" msgid "Invalid DAC pin supplied" msgstr "Ungültiger DAC-Pin angegeben" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Ungültige PWM Frequenz" #: ports/esp32s2/common-hal/analogio/AnalogIn.c msgid "Invalid Pin" -msgstr "" +msgstr "Ungültiger Pin" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c #: py/moduerrno.c shared-module/rgbmatrix/RGBMatrix.c @@ -1208,7 +1260,8 @@ msgstr "Ungültiges Argument" msgid "Invalid bits per value" msgstr "Ungültige Bits pro Wert" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Ungültige Puffergröße" @@ -1237,14 +1290,10 @@ msgstr "Ungültige Datei" msgid "Invalid format chunk size" msgstr "Ungültige format chunk size" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Ungültige Frequenz" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Ungültige Frequenz geliefert" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Ungültiger Speicherzugriff." @@ -1283,17 +1332,13 @@ msgstr "Ungültiger Pin für rechten Kanal" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Ungültige Pins" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Ungültige Pins für PWMOut" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1315,7 +1360,7 @@ msgstr "Ungültiger security_mode" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1323,10 +1368,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "Ungültige Stimme" @@ -1339,14 +1380,11 @@ msgstr "Ungültige Anzahl von Stimmen" msgid "Invalid wave file" msgstr "Ungültige wave Datei" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Ungültige Wort- / Bitlänge" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "Der Schlüssel muss 16, 24 oder 32 Byte lang sein" @@ -1392,15 +1430,6 @@ msgstr "Maximaler x-Wert beim Spiegeln ist %d" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" -"MicroPython NLR-Sprung fehlgeschlagen. Wahrscheinlich Speicherbeschädigung." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Schwerwiegender MicroPython-Fehler." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1453,6 +1482,10 @@ msgstr "Muss MISO- oder MOSI-Pin bereitstellen" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Muss ein Vielfaches von 6 RGB-Pins verwenden, nicht %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1472,9 +1505,15 @@ msgstr "Kein DAC im Chip vorhanden" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Kein DMA Kanal gefunden" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1533,6 +1572,14 @@ msgstr "Keine Hardwareunterstützung am clk Pin" msgid "No hardware support on pin" msgstr "Keine Hardwareunterstützung an diesem Pin" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Es wurde kein Schlüssel angegeben" @@ -1541,18 +1588,6 @@ msgstr "Es wurde kein Schlüssel angegeben" msgid "No long integer support" msgstr "Keine langen Integer (long) unterstützt" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "An diesem Pin sind keine Timer mehr verfügbar." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "" @@ -1561,6 +1596,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "Kein Pulldown Widerstand am Pin; 1Mohm wird vorgeschlagen" @@ -1578,13 +1619,18 @@ msgid "No timer available" msgstr "Kein Timer verfügbar" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Fehlerbehauptung für Nordic Soft Device." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1597,7 +1643,7 @@ msgstr "Spielt nicht ab" #: main.c msgid "Not running saved code.\n" -msgstr "" +msgstr "Gespeicherter Code wird nicht ausgeführt.\n" #: shared-bindings/_bleio/__init__.c msgid "Not settable" @@ -1615,13 +1661,10 @@ msgid "Odd parity is not supported" msgstr "Eine ungerade Parität wird nicht unterstützt" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Nur 8 oder 16 bit mono mit " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1675,10 +1718,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Oversample muss ein Vielfaches von 8 sein." @@ -1697,8 +1749,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "Die PWM-Frequenz ist nicht schreibbar wenn variable_Frequenz = False." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBus wird noch nicht unterstützt" @@ -1734,6 +1793,10 @@ msgstr "Pin hat keine ADC Funktionalität" msgid "Pin is input only" msgstr "Pin kann nur als Eingang verwendet werden" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "Pin muss Hardware-Interrupts unterstützen" @@ -1753,6 +1816,14 @@ msgstr "" "Bytes verbraucht. Wenn dies nicht vermieden werden kann, übergeben Sie " "allow_inefficient = True an den Konstruktor" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "und alle Module im Dateisystem \n" @@ -1783,6 +1854,8 @@ msgstr "Der Präfixbuffer muss sich auf dem Heap befinden" #: main.c msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" msgstr "" +"Drücke eine beliebige Taste um REPL zu betreten. Drücke STRG-D zum " +"neuladen.\n" #: main.c msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" @@ -1824,6 +1897,10 @@ msgstr "RNG DeInit-Fehler" msgid "RNG Init Error" msgstr "RNG Init Fehler" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1831,6 +1908,7 @@ msgstr "RS485-Inversion angegeben, wenn nicht im RS485-Modus" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "Die RTC-Kalibrierung wird auf diesem Board nicht unterstützt" @@ -1839,7 +1917,7 @@ msgid "RTC is not supported on this board" msgstr "Eine RTC wird auf diesem Board nicht unterstützt" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS / CTS / RS485 Wird von diesem Gerät noch nicht unterstützt" @@ -1896,12 +1974,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA oder SCL brauchen pull up" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1937,14 +2009,6 @@ msgstr "Abtastrate zu hoch. Wert muss unter %d liegen" msgid "Scan already in progess. Stop with stop_scan." msgstr "Scannen Sie bereits in Bearbeitung. Stoppen Sie mit stop_scan." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "Ausgewählter CTS-Pin ungültig" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "Ausgewählter RTS-Pin ungültig" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1993,6 +2057,14 @@ msgstr "Splitting mit sub-captures" msgid "Stack size must be at least 256" msgstr "Die Stackgröße sollte mindestens 256 sein" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Stream fehlt readinto() oder write() Methode." @@ -2089,16 +2161,12 @@ msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" "Zeitbeschränkung ist zu groß: Maximale Zeitbeschränkung ist %d Sekunden" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Zum beenden, resette bitte das board ohne " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Zu viele Kanäle im sample." @@ -2111,10 +2179,8 @@ msgid "Too many displays" msgstr "Zu viele displays" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" -"Die Gesamtzahl der zu schreibenden Daten ist größer als " -"outgoing_packet_length" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2140,10 +2206,6 @@ msgstr "UART Init Fehler" msgid "UART Re-init error" msgstr "UART Re-Init-Fehler" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "UART-Schreibfehler" @@ -2170,6 +2232,8 @@ msgstr "Der UUID-Wert ist kein str-, int- oder Byte-Puffer" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Konnte keine Buffer für Vorzeichenumwandlung allozieren" @@ -2207,7 +2271,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "Unerwarteter nrfx uuid-Typ" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2233,8 +2297,8 @@ msgstr "Unbekannter Sicherheitsfehler: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Unbekannter Soft Device-Fehler: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2265,7 +2329,7 @@ msgstr "Nicht unterstützter display bus type" msgid "Unsupported format" msgstr "Nicht unterstütztes Format" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Nicht unterstützte Operation" @@ -2291,10 +2355,6 @@ msgstr "Länge des Wertes > max_length" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper-Funktionen unterstützen derzeit nicht mehr als 4 Argumente" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Zeitüberschreitung beim Lesen der Spannung" @@ -2325,7 +2385,7 @@ msgstr "WatchDogTimer.timeout muss größer als 0 sein" #: supervisor/shared/safe_mode.c msgid "Watchdog timer expired." -msgstr "Watchdog timer abgelaufen " +msgstr "Watchdog timer abgelaufen." #: py/builtinhelp.c #, c-format @@ -2385,11 +2445,6 @@ msgstr "ein Byte-ähnliches Objekt ist erforderlich" msgid "abort() called" msgstr "abort() wurde aufgerufen" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "Addresse %08x ist nicht an %d bytes ausgerichtet" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "Adresse außerhalb der Grenzen" @@ -2398,15 +2453,19 @@ msgstr "Adresse außerhalb der Grenzen" msgid "addresses is empty" msgstr "adresses ist leer" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg ist eine leere Sequenz" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "Das Argument argsort muss ein ndarray sein" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2414,10 +2473,6 @@ msgstr "" msgid "argument has wrong type" msgstr "Argument hat falschen Typ" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "Argument muss ein ndarray sein" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2427,7 +2482,8 @@ msgstr "Anzahl/Typen der Argumente passen nicht" msgid "argument should be a '%q' not a '%q'" msgstr "Argument sollte '%q' sein, nicht '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "Argumente müssen ndarrays sein" @@ -2440,11 +2496,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "Array/Bytes auf der rechten Seite erforderlich" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "Sie haben versucht argmin/argmax von einer leeren Sequenz zu bekommen" @@ -2452,15 +2508,15 @@ msgstr "Sie haben versucht argmin/argmax von einer leeren Sequenz zu bekommen" msgid "attributes not supported yet" msgstr "Attribute werden noch nicht unterstützt" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2485,8 +2541,8 @@ msgid "binary op %q not implemented" msgstr "Der binäre Operator %q ist nicht implementiert" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bits muss 7, 8 oder 9 sein" +msgid "bits must be in range 5 to 9" +msgstr "" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2496,15 +2552,11 @@ msgstr "Es müssen 8 oder 16 bits_per_sample sein" msgid "branch not in range" msgstr "Zweig ist außerhalb der Reichweite" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "Puffer muss ein bytes-artiges Objekt sein" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2521,7 +2573,7 @@ msgstr "Puffersegmente müssen gleich lang sein" msgid "buffer too small" msgstr "Der Puffer ist zu klein" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2589,6 +2641,10 @@ msgstr "kann keinem Ausdruck zuweisen" msgid "can't convert %q to %q" msgstr "kann %q nicht zu %q konvertieren" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "Kann '%q' Objekt nicht implizit nach %q konvertieren" @@ -2597,6 +2653,10 @@ msgstr "Kann '%q' Objekt nicht implizit nach %q konvertieren" msgid "can't convert to %q" msgstr "kann nicht zu %q konvertieren" +#: py/runtime.c +msgid "can't convert to int" +msgstr "kann nicht nach int konvertieren" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "Kann nicht implizit nach str konvertieren" @@ -2721,6 +2781,10 @@ msgstr "chr() arg ist nicht in range(256)" msgid "circle can only be registered in one parent" msgstr "Kreis kann nur in einem Elternteil registriert werden" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2767,19 +2831,19 @@ msgstr "constant muss ein integer sein" msgid "conversion to object" msgstr "Umwandlung zu Objekt" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "Convolve-Argumente müssen lineare Arrays sein" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "Convolve-Argumente müssen ndarrays sein" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "Convolve Argumente dürfen nicht leer sein" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "Vandermonde-Matrix konnte nicht invertiert werden" @@ -2787,15 +2851,15 @@ msgstr "Vandermonde-Matrix konnte nicht invertiert werden" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2834,14 +2898,18 @@ msgstr "destination_length muss ein int >= 0 sein" msgid "dict update sequence has wrong length" msgstr "Die Wörterbuch-Aktualisierungssequenz hat eine falsche Länge" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "diff Argument muss ein ndarray sein" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2902,7 +2970,7 @@ msgstr "erwarte tuple/list" #: py/modthread.c msgid "expecting a dict for keyword args" -msgstr "erwarte ein dict als Keyword-Argumente" +msgstr "erwarte ein dict als Schlüsselwort-Argumente" #: py/compile.c msgid "expecting an assembler instruction" @@ -2922,11 +2990,11 @@ msgstr "" #: py/argcheck.c msgid "extra keyword arguments given" -msgstr "Es wurden zusätzliche Keyword-Argumente angegeben" +msgstr "Es wurden zusätzliche Schlüsselwort-Argumente angegeben" #: py/argcheck.c msgid "extra positional arguments given" -msgstr "Es wurden zusätzliche Argumente ohne Keyword angegeben" +msgstr "Es wurden zusätzliche Argumente ohne Schlüsselwort angegeben" #: py/parse.c msgid "f-string expression part cannot include a '#'" @@ -2949,7 +3017,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: einzelne '}' nicht erlaubt" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "Die Datei muss eine im Byte-Modus geöffnete Datei sein" @@ -2957,11 +3025,11 @@ msgstr "Die Datei muss eine im Byte-Modus geöffnete Datei sein" msgid "filesystem must provide mount method" msgstr "Das Dateisystem muss eine Mount-Methode bereitstellen" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2969,11 +3037,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "Das erste Argument muss iterierbar sein" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "Das erste Argument muss ein Ndarray sein" @@ -2985,7 +3049,7 @@ msgstr "Das erste Argument für super() muss type sein" msgid "flattening order must be either 'C', or 'F'" msgstr "Die Abflachungsreihenfolge muss entweder \"C\" oder \"F\" sein" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "Das Flip-Argument muss ein Ndarray sein" @@ -3006,8 +3070,8 @@ msgid "full" msgstr "voll" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "Funktion akzeptiert keine Keyword-Argumente" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3018,7 +3082,7 @@ msgstr "Funktion erwartet maximal %d Argumente, aber hat %d erhalten" msgid "function got multiple values for argument '%q'" msgstr "Funktion hat mehrere Werte für Argument '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -3029,26 +3093,27 @@ msgstr "" #: py/argcheck.c #, c-format msgid "function missing %d required positional arguments" -msgstr "Funktion vermisst %d benötigte Argumente ohne Keyword" +msgstr "Funktion vermisst %d benötigte Argumente ohne Schlüsselwort" #: py/bc.c msgid "function missing keyword-only argument" -msgstr "Funktion vermisst Keyword-only-Argument" +msgstr "Funktion vermisst Nur-Schlüsselwort-Argument" #: py/bc.c msgid "function missing required keyword argument '%q'" -msgstr "Funktion vermisst benötigtes Keyword-Argumente '%q'" +msgstr "Funktion vermisst benötigtes Schlüsselwort-Argumente '%q'" #: py/bc.c #, c-format msgid "function missing required positional argument #%d" -msgstr "Funktion vermisst benötigtes Argumente ohne Keyword #%d" +msgstr "Funktion vermisst benötigtes Argumente ohne Schlüsselwort #%d" #: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/time/__init__.c #, c-format msgid "function takes %d positional arguments but %d were given" msgstr "" -"Funktion nimmt %d Argumente ohne Keyword an, aber es wurden %d angegeben" +"Funktion nimmt %d Argumente ohne Schlüsselwort an, aber es wurden %d " +"angegeben" #: shared-bindings/time/__init__.c msgid "function takes exactly 9 arguments" @@ -3062,6 +3127,10 @@ msgstr "Generator läuft bereits" msgid "generator ignored GeneratorExit" msgstr "Generator ignoriert GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic muss 2048 Byte lang sein" @@ -3094,8 +3163,9 @@ msgstr "padding ist inkorrekt" msgid "index is out of bounds" msgstr "Index ist außerhalb der Grenzen" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "index außerhalb der Reichweite" @@ -3107,7 +3177,7 @@ msgstr "Indizes müssen Integer sein" msgid "indices must be integers, slices, or Boolean lists" msgstr "Indizes müssen Integer, Slices oder Boolesche Listen sein" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "Ausgangswerte müssen iterierbar sein" @@ -3127,7 +3197,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "Die Länge des Eingabearrays muss eine Potenz von 2 sein" @@ -3135,15 +3205,15 @@ msgstr "Die Länge des Eingabearrays muss eine Potenz von 2 sein" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "Eingabedaten müssen iterierbar sein" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "Eingabematrix ist asymmetrisch" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "Eingabematrix ist singulär" @@ -3159,23 +3229,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "Die Eingabe muss eine quadratische Matrix sein" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "Die Eingabe muss Tupel, Liste, Bereich oder Ndarray sein" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "Eingabevektoren müssen gleich lang sein" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3187,7 +3257,7 @@ msgstr "int() arg 2 muss >= 2 und <= 36 sein" msgid "integer required" msgstr "integer erforderlich" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3200,14 +3270,33 @@ msgstr "Das Intervall muss im Bereich %s-%s sein" msgid "invalid arguments" msgstr "ungültige argumente" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "ungültiges cert" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "ungültiger dupterm index" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "ungültiges Format" @@ -3249,10 +3338,6 @@ msgstr "ungültige Syntax für integer mit Basis %d" msgid "invalid syntax for number" msgstr "ungültige Syntax für number" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 muss eine Klasse sein" @@ -3261,11 +3346,7 @@ msgstr "issubclass() arg 1 muss eine Klasse sein" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass() arg 2 muss eine Klasse oder ein Tupel von Klassen sein" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "iterables sind nicht gleich lang" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "Iterationen sind nicht konvergiert (converged)" @@ -3278,8 +3359,8 @@ msgstr "" #: py/argcheck.c msgid "keyword argument(s) not yet implemented - use normal args instead" msgstr "" -"Keyword-Argument(e) noch nicht implementiert - verwenden Sie stattdessen " -"normale Argumente" +"Schlüsselwort-Argument(e) noch nicht implementiert - verwenden Sie " +"stattdessen normale Argumente" #: py/bc.c msgid "keywords must be strings" @@ -3339,11 +3420,7 @@ msgstr "map buffer zu klein" msgid "math domain error" msgstr "Mathe-Domain-Fehler" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "Matrix Dimensionen stimmen nicht überein" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "Matrix ist nicht positiv definitiv" @@ -3365,15 +3442,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "maximale Rekursionstiefe überschritten" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3386,11 +3463,15 @@ msgstr "Speicherzuordnung fehlgeschlagen, Zuweisung von %u Bytes" msgid "memory allocation failed, heap is locked" msgstr "Speicherzuweisung fehlgeschlagen, der Heap ist gesperrt" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "Modul nicht gefunden" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "mehr Freiheitsgrade als Datenpunkte" @@ -3435,6 +3516,10 @@ msgstr "native Ausbeute (yield)" msgid "need more than %d values to unpack" msgstr "Zum Entpacken sind mehr als %d Werte erforderlich" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negative Potenz ohne Gleitkomma (float) Unterstützung" @@ -3508,10 +3593,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "keine 128-bit UUID" @@ -3581,7 +3662,7 @@ msgstr "Objekt mit Pufferprotokoll (buffer protocol) erforderlich" msgid "odd-length string" msgstr "String mit ungerader Länge" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3611,8 +3692,8 @@ msgid "only slices with step=1 (aka None) are supported" msgstr "" "Es werden nur Slices mit Schritt = 1 (auch bekannt als None) unterstützt" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "Operanden konnten nicht zusammen gesendet werden" @@ -3620,7 +3701,7 @@ msgstr "Operanden konnten nicht zusammen gesendet werden" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "Die Operation ist für ndarrays nicht implementiert" @@ -3639,11 +3720,19 @@ msgstr "" "ord() erwartet einen Buchstaben(char) aber es wurde ein String mit Länge %d " "gefunden" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "Außerhalb des Bereichs der Quelle" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "Außerhalb des Bereichs des Ziels" @@ -3664,10 +3753,6 @@ msgstr "Die Palette muss 32 Byte lang sein" msgid "palette_index should be an int" msgstr "palette_index sollte ein int sein" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parameter annotation muss ein identifier sein" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "Die Parameter müssen Register der Reihenfolge a2 bis a5 sein" @@ -3676,7 +3761,7 @@ msgstr "Die Parameter müssen Register der Reihenfolge a2 bis a5 sein" msgid "parameters must be registers in sequence r0 to r3" msgstr "Die Parameter müssen Register der Reihenfolge r0 bis r3 sein" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "Pixelkoordinaten außerhalb der Grenzen" @@ -3699,11 +3784,16 @@ msgstr "pop von einem leeren PulseIn" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "pow() drittes Argument darf nicht 0 sein" @@ -3714,12 +3804,17 @@ msgstr "pow () mit 3 Argumenten erfordert Integer" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3727,6 +3822,7 @@ msgstr "pow () mit 3 Argumenten erfordert Integer" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3738,6 +3834,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3754,7 +3858,7 @@ msgstr "Warteschlangenüberlauf" msgid "raw f-strings are not implemented" msgstr "rohe F-Strings sind nicht implementiert" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "Real- und Imaginärteile müssen gleich lang sein" @@ -3789,7 +3893,7 @@ msgstr "rgb_pins[%d] dupliziert eine andere Pinbelegung" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins [%d] befindet sich nicht am selben Port wie clock" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3806,6 +3910,7 @@ msgstr "" "oder 'B' sein" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "Abtastrate außerhalb der Reichweite" @@ -3837,7 +3942,7 @@ msgstr "Vorzeichen mit ganzzahligem Formatbezeichner 'c' nicht erlaubt" msgid "single '}' encountered in format string" msgstr "einzelne '}' in Formatierungs-String gefunden" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "Größe ist nur für ndarrays definiert" @@ -3861,23 +3966,23 @@ msgstr "small int Überlauf" msgid "soft reboot\n" msgstr "weicher reboot\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "sortierungs Argument muss ein ndarray sein" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "Quell-Palette zu groß" @@ -3988,7 +4093,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "zu viele Argumente mit dem angegebenen Format" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -4001,18 +4106,14 @@ msgstr "zu viele Indizes" msgid "too many values to unpack (expected %d)" msgstr "zu viele Werte zum Auspacken (erwartet %d)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupel/list hat falsche Länge" @@ -4069,11 +4170,11 @@ msgstr "" #: py/bc.c msgid "unexpected keyword argument" -msgstr "unerwartetes Keyword-Argument" +msgstr "unerwartetes Schlüsselwort-Argument" #: py/bc.c py/objnamedtuple.c msgid "unexpected keyword argument '%q'" -msgstr "unerwartetes Keyword-Argument '%q'" +msgstr "unerwartetes Schlüsselwort-Argument '%q'" #: py/lexer.c msgid "unicode name escapes" @@ -4098,7 +4199,7 @@ msgstr "Unbekannter Formatcode '%c' für Objekt vom Typ '%q'" msgid "unknown type" msgstr "unbekannter Typ" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "unbekannter Typ '%q'" @@ -4151,14 +4252,6 @@ msgstr "Wert muss in %d Byte(s) passen" msgid "value_count must be > 0" msgstr "value_count muss größer als 0 sein" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "Vektoren müssen die selbe Länge haben" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4167,6 +4260,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4179,7 +4277,7 @@ msgstr "" msgid "window must be <= interval" msgstr "Fenster muss <= Intervall sein" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4187,7 +4285,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "falscher Eingabetyp" @@ -4203,7 +4302,7 @@ msgstr "falsche Anzahl zu entpackender Werte" msgid "wrong operand type" msgstr "falscher Operandentyp" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "Falscher Ausgabetyp" @@ -4227,18 +4326,105 @@ msgstr "y Wert außerhalb der Grenzen" msgid "zero step" msgstr "Nullschritt" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper-Funktionen unterstützen derzeit nicht mehr als 4 Argumente" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "Addresse %08x ist nicht an %d bytes ausgerichtet" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "Funktion akzeptiert keine Schlüsselwort-Argumente" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotation muss ein identifier sein" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Die Gesamtzahl der zu schreibenden Daten ist größer als " +#~ "outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 & 4 unterstützen keinen internen Pull up im sleep-Modus" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "Puffer muss ein bytes-artiges Objekt sein" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "Versuch einer Heap Reservierung, wenn die MicroPython-VM nicht ausgeführt " +#~ "wird." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "" +#~ "MicroPython NLR-Sprung fehlgeschlagen. Wahrscheinlich " +#~ "Speicherbeschädigung." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Schwerwiegender MicroPython-Fehler." + +#~ msgid "argument must be ndarray" +#~ msgstr "Argument muss ein ndarray sein" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "Matrix Dimensionen stimmen nicht überein" + +#~ msgid "vectors must have same lengths" +#~ msgstr "Vektoren müssen die selbe Länge haben" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Fehlerbehauptung für Nordic Soft Device." + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Unbekannter Soft Device-Fehler: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "Das erste Argument muss iterierbar sein" + +#~ msgid "iterables are not of the same length" +#~ msgstr "iterables sind nicht gleich lang" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Ausgewählter CTS-Pin ungültig" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Ausgewählter RTS-Pin ungültig" + +#~ msgid "Could not initialize channel" +#~ msgstr "Kanal konnte nicht initialisiert werden" + +#~ msgid "Could not initialize timer" +#~ msgstr "Timer konnte nicht initialisiert werden" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Ungültige Frequenz geliefert" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Ungültige Pins für PWMOut" + +#~ msgid "No more timers available on this pin." +#~ msgstr "An diesem Pin sind keine Timer mehr verfügbar." + +#~ msgid "Group full" +#~ msgstr "Gruppe voll" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bits muss 7, 8 oder 9 sein" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA oder SCL brauchen pull up" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "" #~ "%d Adress-Pins und %d rgb-Pins zeigen eine Höhe von %d, nicht von %d" @@ -4397,9 +4583,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "kann nicht nach float konvertieren" -#~ msgid "can't convert to int" -#~ msgstr "kann nicht nach int konvertieren" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "Objekt '%s' ist weder tupel noch list" diff --git a/locale/el.po b/locale/el.po index 0c7cb5f6bb481..93d1c14efecab 100644 --- a/locale/el.po +++ b/locale/el.po @@ -73,6 +73,7 @@ msgstr "" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -102,6 +103,7 @@ msgstr "" msgid "%q must be a tuple of length 2" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "" @@ -332,9 +334,14 @@ msgid "All SPI peripherals are in use" msgstr "" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "" @@ -363,6 +370,7 @@ msgstr "" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "" @@ -403,6 +411,10 @@ msgstr "" msgid "AnalogOut not supported on given pin" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -426,7 +438,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -452,6 +464,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "" @@ -493,6 +509,10 @@ msgstr "" msgid "Buffer + offset too small %d %d %d" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -509,6 +529,7 @@ msgid "Buffer is too small" msgstr "" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "" @@ -538,6 +559,7 @@ msgstr "" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "" @@ -629,6 +651,10 @@ msgstr "" msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "" @@ -650,7 +676,7 @@ msgstr "" msgid "Cannot unambiguously get sizeof scalar" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" @@ -732,14 +758,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "" @@ -760,7 +778,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "" @@ -861,11 +879,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -916,15 +939,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -938,6 +961,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "" @@ -946,6 +970,7 @@ msgstr "" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -959,6 +984,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "" @@ -984,6 +1013,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1007,7 +1040,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1026,10 +1059,6 @@ msgstr "" msgid "Group already used" msgstr "" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1060,15 +1089,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1083,10 +1112,23 @@ msgstr "" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1143,6 +1185,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "" @@ -1169,8 +1212,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "" @@ -1188,7 +1237,8 @@ msgstr "" msgid "Invalid bits per value" msgstr "" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "" @@ -1217,14 +1267,10 @@ msgstr "" msgid "Invalid format chunk size" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "" @@ -1263,17 +1309,13 @@ msgstr "" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1295,7 +1337,7 @@ msgstr "" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1303,10 +1345,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1319,14 +1357,11 @@ msgstr "" msgid "Invalid wave file" msgstr "" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "" @@ -1372,14 +1407,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1431,6 +1458,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1450,9 +1481,15 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1511,24 +1548,20 @@ msgstr "" msgid "No hardware support on pin" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "No key was specified" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" +#: shared-bindings/aesio/aes.c +msgid "No key was specified" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." +#: shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" #: shared-bindings/wifi/Radio.c @@ -1539,6 +1572,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1556,13 +1595,18 @@ msgid "No timer available" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1591,13 +1635,10 @@ msgid "Odd parity is not supported" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1647,10 +1688,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "" @@ -1669,8 +1719,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "" @@ -1706,6 +1763,10 @@ msgstr "" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "" @@ -1722,6 +1783,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "" @@ -1793,6 +1862,10 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1800,6 +1873,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "" @@ -1808,7 +1882,7 @@ msgid "RTC is not supported on this board" msgstr "" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "" @@ -1865,12 +1939,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1906,14 +1974,6 @@ msgstr "" msgid "Scan already in progess. Stop with stop_scan." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1962,6 +2022,14 @@ msgstr "" msgid "Stack size must be at least 256" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "" @@ -2046,16 +2114,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "" @@ -2068,7 +2132,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2095,10 +2159,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "" @@ -2125,6 +2185,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "" @@ -2162,7 +2224,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2188,7 +2250,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2216,7 +2278,7 @@ msgstr "" msgid "Unsupported format" msgstr "" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "" @@ -2242,10 +2304,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2325,11 +2383,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2338,15 +2391,19 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2354,10 +2411,6 @@ msgstr "" msgid "argument has wrong type" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2367,7 +2420,8 @@ msgstr "" msgid "argument should be a '%q' not a '%q'" msgstr "" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2380,11 +2434,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2392,15 +2446,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2425,7 +2479,7 @@ msgid "binary op %q not implemented" msgstr "" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" +msgid "bits must be in range 5 to 9" msgstr "" #: shared-bindings/audiomixer/Mixer.c @@ -2436,15 +2490,11 @@ msgstr "" msgid "branch not in range" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2461,7 +2511,7 @@ msgstr "" msgid "buffer too small" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2527,6 +2577,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2535,6 +2589,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2653,6 +2711,10 @@ msgstr "" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2697,19 +2759,19 @@ msgstr "" msgid "conversion to object" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2717,15 +2779,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2762,14 +2824,18 @@ msgstr "" msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2877,7 +2943,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2885,11 +2951,11 @@ msgstr "" msgid "filesystem must provide mount method" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2897,11 +2963,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2913,7 +2975,7 @@ msgstr "" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2934,7 +2996,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -2946,7 +3008,7 @@ msgstr "" msgid "function got multiple values for argument '%q'" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -2989,6 +3051,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3021,8 +3087,9 @@ msgstr "" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "" @@ -3034,7 +3101,7 @@ msgstr "" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3054,7 +3121,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3062,15 +3129,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3086,23 +3153,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3114,7 +3181,7 @@ msgstr "" msgid "integer required" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3127,14 +3194,33 @@ msgstr "" msgid "invalid arguments" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "" @@ -3176,10 +3262,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3188,11 +3270,7 @@ msgstr "" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3260,11 +3338,7 @@ msgstr "" msgid "math domain error" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3286,15 +3360,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3307,11 +3381,15 @@ msgstr "" msgid "memory allocation failed, heap is locked" msgstr "" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3356,6 +3434,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3429,10 +3511,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3501,7 +3579,7 @@ msgstr "" msgid "odd-length string" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3530,8 +3608,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3539,7 +3617,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3556,11 +3634,19 @@ msgstr "" msgid "ord() expected a character, but string of length %d found" msgstr "" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3581,10 +3667,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3593,7 +3675,7 @@ msgstr "" msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "" @@ -3616,11 +3698,16 @@ msgstr "" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "" @@ -3631,12 +3718,17 @@ msgstr "" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3644,6 +3736,7 @@ msgstr "" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3655,6 +3748,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3671,7 +3772,7 @@ msgstr "" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3706,7 +3807,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3721,6 +3822,7 @@ msgid "" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "" @@ -3752,7 +3854,7 @@ msgstr "" msgid "single '}' encountered in format string" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3776,23 +3878,23 @@ msgstr "" msgid "soft reboot\n" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3902,7 +4004,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3915,18 +4017,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4008,7 +4106,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4061,14 +4159,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4077,6 +4167,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4089,7 +4184,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4097,7 +4192,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4113,7 +4209,7 @@ msgstr "" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4137,14 +4233,14 @@ msgstr "" msgid "zero step" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" diff --git a/locale/en_GB.po b/locale/en_GB.po new file mode 100644 index 0000000000000..f3fd1e71ad064 --- /dev/null +++ b/locale/en_GB.po @@ -0,0 +1,4360 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"PO-Revision-Date: 2021-04-11 01:30+0000\n" +"Last-Translator: Hugo Dahl \n" +"Language-Team: none\n" +"Language: en_GB\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=n != 1;\n" +"X-Generator: Weblate 4.6-dev\n" + +#: main.c +msgid "" +"\n" +"Code done running.\n" +msgstr "" +"\n" +"Code done running.\n" + +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload.\n" +msgstr "" +"\n" +"Code stopped by auto-reload.\n" + +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Please file an issue with the contents of your CIRCUITPY drive at \n" +"https://github.com/adafruit/circuitpython/issues\n" +msgstr "" +"\n" +"Please file an issue with the contents of your CIRCUITPY drive at \n" +"https://github.com/adafruit/circuitpython/issues\n" + +#: py/obj.c +msgid " File \"%q\"" +msgstr " File \"%q\"" + +#: py/obj.c +msgid " File \"%q\", line %d" +msgstr " File \"%q\", line %d" + +#: py/builtinhelp.c +msgid " is of type %q\n" +msgstr " is of type %q\n" + +#: main.c +msgid " output:\n" +msgstr " output:\n" + +#: py/objstr.c +#, c-format +msgid "%%c requires int or char" +msgstr "%%c requires int or char" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "" +"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" +msgstr "" +"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +msgid "%q failure: %d" +msgstr "%q failure: %d" + +#: shared-bindings/microcontroller/Pin.c +msgid "%q in use" +msgstr "%q in use" + +#: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c +#: py/objstrunicode.c +msgid "%q index out of range" +msgstr "%q index out of range" + +#: py/obj.c +msgid "%q indices must be integers, not %q" +msgstr "%q indices must be integers, not %q" + +#: shared-bindings/vectorio/Polygon.c +msgid "%q list must be a list" +msgstr "%q list must be a list" + +#: shared-bindings/memorymonitor/AllocationAlarm.c +msgid "%q must be >= 0" +msgstr "%q must be >= 0" + +#: shared-bindings/_bleio/CharacteristicBuffer.c +#: shared-bindings/_bleio/PacketBuffer.c shared-bindings/displayio/Group.c +#: shared-bindings/displayio/Shape.c +#: shared-bindings/memorymonitor/AllocationAlarm.c +#: shared-bindings/vectorio/Circle.c shared-bindings/vectorio/Rectangle.c +msgid "%q must be >= 1" +msgstr "%q must be >= 1" + +#: shared-module/vectorio/Polygon.c +msgid "%q must be a tuple of length 2" +msgstr "%q must be a tuple of length 2" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: shared-bindings/canio/Match.c +msgid "%q out of range" +msgstr "%q out of range" + +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +msgid "%q pin invalid" +msgstr "%q pin invalid" + +#: shared-bindings/fontio/BuiltinFont.c +msgid "%q should be an int" +msgstr "%q should be an int" + +#: py/bc.c py/objnamedtuple.c +msgid "%q() takes %d positional arguments but %d were given" +msgstr "%q() takes %d positional arguments but %d were given" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +#, c-format +msgid "%s error 0x%x" +msgstr "%s error 0x%x" + +#: py/argcheck.c +msgid "'%q' argument required" +msgstr "'%q' argument required" + +#: py/runtime.c +msgid "'%q' object cannot assign attribute '%q'" +msgstr "'%q' object cannot assign attribute '%q'" + +#: py/proto.c +msgid "'%q' object does not support '%q'" +msgstr "'%q' object does not support '%q'" + +#: py/obj.c +msgid "'%q' object does not support item assignment" +msgstr "'%q' object does not support item assignment" + +#: py/obj.c +msgid "'%q' object does not support item deletion" +msgstr "'%q' object does not support item deletion" + +#: py/runtime.c +msgid "'%q' object has no attribute '%q'" +msgstr "'%q' object has no attribute '%q'" + +#: py/runtime.c +msgid "'%q' object is not an iterator" +msgstr "'%q' object is not an iterator" + +#: py/objtype.c py/runtime.c +msgid "'%q' object is not callable" +msgstr "'%q' object is not callable" + +#: py/runtime.c +msgid "'%q' object is not iterable" +msgstr "'%q' object is not iterable" + +#: py/obj.c +msgid "'%q' object is not subscriptable" +msgstr "'%q' object is not subscriptable" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a label" +msgstr "'%s' expects a label" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a register" +msgstr "'%s' expects a register" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects a special register" +msgstr "'%s' expects a special register" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an FPU register" +msgstr "'%s' expects an FPU register" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an address of the form [a, b]" +msgstr "'%s' expects an address of the form [a, b]" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects an integer" +msgstr "'%s' expects an integer" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects at most r%d" +msgstr "'%s' expects at most r%d" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects {r0, r1, ...}" +msgstr "'%s' expects {r0, r1, ...}" + +#: py/emitinlinextensa.c +#, c-format +msgid "'%s' integer %d is not within range %d..%d" +msgstr "'%s' integer %d is not within range %d..%d" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' integer 0x%x does not fit in mask 0x%x" +msgstr "'%s' integer 0x%x does not fit in mask 0x%x" + +#: py/objstr.c +msgid "'=' alignment not allowed in string format specifier" +msgstr "'=' alignment not allowed in string format specifier" + +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" +msgstr "'S' and 'O' are not supported format types" + +#: py/compile.c +msgid "'align' requires 1 argument" +msgstr "'align' requires 1 argument" + +#: py/compile.c +msgid "'await' outside function" +msgstr "'await' outside function" + +#: py/compile.c +msgid "'await', 'async for' or 'async with' outside async function" +msgstr "'await', 'async for' or 'async with' outside async function" + +#: py/compile.c +msgid "'break' outside loop" +msgstr "'break' outside loop" + +#: py/compile.c +msgid "'continue' outside loop" +msgstr "'continue' outside loop" + +#: py/objgenerator.c +msgid "'coroutine' object is not an iterator" +msgstr "'coroutine' object is not an iterator" + +#: py/compile.c +msgid "'data' requires at least 2 arguments" +msgstr "'data' requires at least 2 arguments" + +#: py/compile.c +msgid "'data' requires integer arguments" +msgstr "'data' requires integer arguments" + +#: py/compile.c +msgid "'label' requires 1 argument" +msgstr "'label' requires 1 argument" + +#: py/compile.c +msgid "'return' outside function" +msgstr "'return' outside function" + +#: py/compile.c +msgid "'yield from' inside async function" +msgstr "'yield from' inside async function" + +#: py/compile.c +msgid "'yield' outside function" +msgstr "'yield' outside function" + +#: py/compile.c +msgid "*x must be assignment target" +msgstr "*x must be assignment target" + +#: py/obj.c +msgid ", in %q\n" +msgstr ", in %q\n" + +#: py/objcomplex.c +msgid "0.0 to a complex power" +msgstr "0.0 to a complex power" + +#: py/modbuiltins.c +msgid "3-arg pow() not supported" +msgstr "3-arg pow() not supported" + +#: shared-module/msgpack/__init__.c +msgid "64 bit types" +msgstr "64 bit types" + +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +msgid "A hardware interrupt channel is already in use" +msgstr "A hardware interrupt channel is already in use" + +#: ports/esp32s2/common-hal/analogio/AnalogIn.c +msgid "ADC2 is being used by WiFi" +msgstr "ADC2 is being used by WiFi" + +#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c +#, c-format +msgid "Address must be %d bytes long" +msgstr "Address must be %d bytes long" + +#: shared-bindings/_bleio/Address.c +msgid "Address type out of range" +msgstr "Address type out of range" + +#: ports/esp32s2/common-hal/canio/CAN.c +msgid "All CAN peripherals are in use" +msgstr "All CAN peripherals are in use" + +#: ports/esp32s2/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" +msgstr "All I2C peripherals are in use" + +#: ports/esp32s2/common-hal/countio/Counter.c +#: ports/esp32s2/common-hal/frequencyio/FrequencyIn.c +#: ports/esp32s2/common-hal/rotaryio/IncrementalEncoder.c +msgid "All PCNT units in use" +msgstr "All PCNT units in use" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/esp32s2/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "All RX FIFOs in use" +msgstr "All RX FIFOs in use" + +#: ports/esp32s2/common-hal/busio/SPI.c ports/nrf/common-hal/busio/SPI.c +msgid "All SPI peripherals are in use" +msgstr "All SPI peripherals are in use" + +#: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "All UART peripherals are in use" + +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "All channels in use" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "All event channels in use" +msgstr "All event channels in use" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "All state machines in use" +msgstr "All state machines in use" + +#: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "All sync event channels in use" +msgstr "All sync event channels in use" + +#: shared-bindings/pwmio/PWMOut.c +msgid "All timers for this pin are in use" +msgstr "All timers for this pin are in use" + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +#: ports/esp32s2/common-hal/frequencyio/FrequencyIn.c +#: ports/esp32s2/common-hal/neopixel_write/__init__.c +#: ports/esp32s2/common-hal/pulseio/PulseIn.c +#: ports/esp32s2/common-hal/pulseio/PulseOut.c +#: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c +msgid "All timers in use" +msgstr "All timers in use" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "Already advertising." +msgstr "Already advertising." + +#: ports/atmel-samd/common-hal/canio/Listener.c +msgid "Already have all-matches listener" +msgstr "Already have all-matches listener" + +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "Already running" + +#: ports/esp32s2/common-hal/wifi/Radio.c +msgid "Already scanning for wifi networks" +msgstr "Already scanning for WiFi networks" + +#: ports/cxd56/common-hal/analogio/AnalogIn.c +msgid "AnalogIn not supported on given pin" +msgstr "AnalogIn not supported on given pin" + +#: ports/cxd56/common-hal/analogio/AnalogOut.c +#: ports/mimxrt10xx/common-hal/analogio/AnalogOut.c +#: ports/nrf/common-hal/analogio/AnalogOut.c +#: ports/raspberrypi/common-hal/analogio/AnalogOut.c +msgid "AnalogOut functionality not supported" +msgstr "AnalogOut functionality not supported" + +#: shared-bindings/analogio/AnalogOut.c +msgid "AnalogOut is only 16 bits. Value must be less than 65536." +msgstr "AnalogOut is only 16 bits. Value must be less than 65536." + +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +msgid "AnalogOut not supported on given pin" +msgstr "AnalogOut not supported on given pin" + +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "Another send is already active" + +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" +msgstr "Array must contain halfwords (type 'H')" + +#: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c +msgid "Array values should be single bytes." +msgstr "Array values should be single bytes." + +#: shared-bindings/microcontroller/Pin.c +msgid "At most %d %q may be specified (not %d)" +msgstr "At most %d %q may be specified (not %d)" + +#: shared-module/memorymonitor/AllocationAlarm.c +#, c-format +msgid "Attempt to allocate %d blocks" +msgstr "Attempt to allocate %d blocks" + +#: supervisor/shared/safe_mode.c +msgid "Attempted heap allocation when VM not running." +msgstr "" + +#: shared-bindings/wifi/Radio.c +msgid "Authentication failure" +msgstr "Authentication failure" + +#: main.c +msgid "Auto-reload is off.\n" +msgstr "Auto-reload is off.\n" + +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" +msgstr "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" + +#: ports/esp32s2/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" +msgstr "Baudrate not supported by peripheral" + +#: shared-module/displayio/Display.c +#: shared-module/framebufferio/FramebufferDisplay.c +msgid "Below minimum frame rate" +msgstr "Below minimum frame rate" + +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "Bit clock and word select must be sequential pins" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must share a clock unit" +msgstr "Bit clock and word select must share a clock unit" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Bit depth must be from 1 to 6 inclusive, not %d" +msgstr "Bit depth must be from 1 to 6 inclusive, not %d" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "Bit depth must be multiple of 8." +msgstr "Bit depth must be multiple of 8." + +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "Both RX and TX required for flow control" + +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +msgid "Both pins must support hardware interrupts" +msgstr "Both pins must support hardware interrupts" + +#: shared-bindings/displayio/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "Brightness must be 0-1.0" +msgstr "Brightness must be 0-1.0" + +#: shared-bindings/supervisor/__init__.c +msgid "Brightness must be between 0 and 255" +msgstr "Brightness must be between 0 and 255" + +#: shared-bindings/displayio/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" +msgstr "Brightness not adjustable" + +#: shared-bindings/_bleio/UUID.c +#, c-format +msgid "Buffer + offset too small %d %d %d" +msgstr "Buffer + offset too small %d %d %d" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Buffer elements must be 4 bytes long or less" + +#: shared-module/usb_hid/Device.c +#, c-format +msgid "Buffer incorrect size. Should be %d bytes." +msgstr "Buffer incorrect size. Should be %d bytes." + +#: shared-bindings/displayio/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." +msgstr "Buffer is not a bytearray." + +#: ports/cxd56/common-hal/camera/Camera.c shared-bindings/displayio/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is too small" +msgstr "Buffer is too small" + +#: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#, c-format +msgid "Buffer length %d too big. It must be less than %d" +msgstr "Buffer length %d too big. It must be less than %d" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/cxd56/common-hal/sdioio/SDCard.c shared-module/sdcardio/SDCard.c +msgid "Buffer length must be a multiple of 512" +msgstr "Buffer length must be a multiple of 512" + +#: ports/stm/common-hal/sdioio/SDCard.c +msgid "Buffer must be a multiple of 512 bytes" +msgstr "Buffer must be a multiple of 512 bytes" + +#: shared-bindings/bitbangio/I2C.c shared-bindings/busio/I2C.c +msgid "Buffer must be at least length 1" +msgstr "Buffer must be at least length 1" + +#: ports/nrf/common-hal/_bleio/PacketBuffer.c +msgid "Buffer too large and unable to allocate" +msgstr "Buffer too large and unable to allocate" + +#: shared-bindings/_bleio/PacketBuffer.c +#, c-format +msgid "Buffer too short by %d bytes" +msgstr "Buffer too short by %d bytes" + +#: ports/atmel-samd/common-hal/displayio/ParallelBus.c +#: ports/esp32s2/common-hal/displayio/ParallelBus.c +#: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c +#, c-format +msgid "Bus pin %d is already in use" +msgstr "Bus pin %d is already in use" + +#: shared-bindings/_bleio/UUID.c +msgid "Byte buffer must be 16 bytes." +msgstr "Byte buffer must be 16 bytes." + +#: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c +msgid "Bytes must be between 0 and 255." +msgstr "Bytes must be between 0 and 255." + +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" +msgstr "CBC blocks must be multiples of 16 bytes" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "CRC or checksum was invalid" +msgstr "CRC or checksum was invalid" + +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." +msgstr "Call super().__init__() before accessing native object." + +#: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." +msgstr "Can only alarm on RTC IO from deep sleep." + +#: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." +msgstr "Can only alarm on one low pin while others alarm high from deep sleep." + +#: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." +msgstr "Can only alarm on two low pins from deep sleep." + +#: ports/nrf/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "Can't set CCCD on local Characteristic" + +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" +msgstr "Cannot create a new Adapter; use _bleio.adapter;" + +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" +msgstr "Cannot delete values" + +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nrf/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "Cannot get pull while in output mode" + +#: ports/nrf/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" +msgstr "Cannot get temperature" + +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot have scan responses for extended, connectable advertisements." +msgstr "Cannot have scan responses for extended, connectable advertisements." + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Cannot output both channels on the same pin" +msgstr "Cannot output both channels on the same pin" + +#: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." +msgstr "Cannot pull on input-only pin." + +#: shared-module/bitbangio/SPI.c +msgid "Cannot read without MISO pin." +msgstr "Cannot read without MISO pin." + +#: shared-bindings/audiobusio/PDMIn.c +msgid "Cannot record to a file" +msgstr "Cannot record to a file" + +#: shared-module/storage/__init__.c +msgid "Cannot remount '/' when USB is active." +msgstr "Cannot remount '/' when USB is active." + +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "Cannot reset into bootloader because no bootloader is present." +msgstr "Cannot reset into bootloader because no bootloader is present." + +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "Cannot set socket options" + +#: shared-bindings/digitalio/DigitalInOut.c +msgid "Cannot set value when direction is input." +msgstr "Cannot set value when direction is input." + +#: ports/esp32s2/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Cannot specify RTS or CTS in RS485 mode" +msgstr "Cannot specify RTS or CTS in RS485 mode" + +#: py/objslice.c +msgid "Cannot subclass slice" +msgstr "Cannot subclass slice" + +#: shared-module/bitbangio/SPI.c +msgid "Cannot transfer without MOSI and MISO pins." +msgstr "Cannot transfer without MOSI and MISO pins." + +#: extmod/moductypes.c +msgid "Cannot unambiguously get sizeof scalar" +msgstr "Cannot unambiguously get sizeof scalar" + +#: shared-bindings/pwmio/PWMOut.c +msgid "Cannot vary frequency on a timer that is already in use" +msgstr "Cannot vary frequency on a timer that is already in use" + +#: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge. Only level." +msgstr "Cannot wake on pin edge. Only level." + +#: shared-module/bitbangio/SPI.c +msgid "Cannot write without MOSI pin." +msgstr "Cannot write without MOSI pin." + +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" +msgstr "CharacteristicBuffer writing not provided" + +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" +msgstr "CircuitPython core code crashed hard. Crikey!\n" + +#: supervisor/shared/safe_mode.c +msgid "" +"CircuitPython is in safe mode because you pressed the reset button during " +"boot. Press again to exit safe mode.\n" +msgstr "" +"CircuitPython is in safe mode because you pressed the reset button during " +"boot. Press again to exit safe mode.\n" + +#: supervisor/shared/safe_mode.c +msgid "CircuitPython was unable to allocate the heap.\n" +msgstr "CircuitPython was unable to allocate the heap.\n" + +#: shared-module/bitbangio/SPI.c +msgid "Clock pin init failed." +msgstr "Clock pin init failed." + +#: shared-module/bitbangio/I2C.c +msgid "Clock stretch too long" +msgstr "Clock stretch too long" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "Clock unit in use" + +#: shared-bindings/_pew/PewPew.c +msgid "Column entry must be digitalio.DigitalInOut" +msgstr "Column entry must be digitalio.DigitalInOut" + +#: shared-bindings/displayio/FourWire.c shared-bindings/displayio/I2CDisplay.c +#: shared-bindings/displayio/ParallelBus.c +msgid "Command must be an int between 0 and 255" +msgstr "Command must be an int between 0 and 255" + +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." +msgstr "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." + +#: py/persistentcode.c +msgid "Corrupt .mpy file" +msgstr "Corrupt .mpy file" + +#: py/emitglue.c +msgid "Corrupt raw code" +msgstr "Corrupt raw code" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Could not initialize Camera" +msgstr "Could not initialise camera" + +#: ports/cxd56/common-hal/gnss/GNSS.c +msgid "Could not initialize GNSS" +msgstr "Could not initialise GNSS" + +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "Could not initialize SDCard" +msgstr "Could not initialise SDCard" + +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/esp32s2/common-hal/busio/UART.c +msgid "Could not initialize UART" +msgstr "Could not initialise UART" + +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "Could not re-init channel" +msgstr "Could not reinit channel" + +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "Could not re-init timer" +msgstr "Could not reinit timer" + +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "Could not restart PWM" +msgstr "Could not restart PWM" + +#: ports/esp32s2/common-hal/neopixel_write/__init__.c +msgid "Could not retrieve clock" +msgstr "Could not retrieve clock" + +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" +msgstr "Could not set address" + +#: shared-bindings/pwmio/PWMOut.c +msgid "Could not start PWM" +msgstr "Could not start PWM" + +#: ports/stm/common-hal/busio/UART.c +msgid "Could not start interrupt, RX busy" +msgstr "Could not start interrupt, RX busy" + +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" +msgstr "Couldn't allocate decoder" + +#: shared-module/audiocore/WaveFile.c shared-module/audiomixer/Mixer.c +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate first buffer" +msgstr "Couldn't allocate first buffer" + +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate input buffer" +msgstr "Couldn't allocate input buffer" + +#: shared-module/audiocore/WaveFile.c shared-module/audiomixer/Mixer.c +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate second buffer" +msgstr "Couldn't allocate second buffer" + +#: supervisor/shared/safe_mode.c +msgid "Crash into the HardFault_Handler." +msgstr "Crash into the HardFault_Handler." + +#: ports/stm/common-hal/analogio/AnalogOut.c +msgid "DAC Channel Init Error" +msgstr "DAC channel init error" + +#: ports/stm/common-hal/analogio/AnalogOut.c +msgid "DAC Device Init Error" +msgstr "DAC device init error" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "DAC already in use" +msgstr "DAC already in use" + +#: ports/atmel-samd/common-hal/displayio/ParallelBus.c +#: ports/nrf/common-hal/displayio/ParallelBus.c +msgid "Data 0 pin must be byte aligned" +msgstr "Data 0 pin must be byte aligned" + +#: ports/esp32s2/common-hal/displayio/ParallelBus.c +msgid "Data 0 pin must be byte aligned." +msgstr "Data 0 pin must be byte aligned." + +#: shared-module/audiocore/WaveFile.c +msgid "Data chunk must follow fmt chunk" +msgstr "Data chunk must follow fmt chunk" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "Data too large for advertisement packet" +msgstr "Data too large for advertisement packet" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "Destination capacity is smaller than destination_length." +msgstr "Destination capacity is smaller than destination_length." + +#: ports/nrf/common-hal/audiobusio/I2SOut.c +msgid "Device in use" +msgstr "Device in use" + +#: ports/cxd56/common-hal/digitalio/DigitalInOut.c +msgid "DigitalInOut not supported on given pin" +msgstr "DigitalInOut not supported on given pin" + +#: shared-bindings/displayio/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display must have a 16 bit colorspace." +msgstr "Display must have a 16 bit colourspace." + +#: shared-bindings/displayio/Display.c +#: shared-bindings/displayio/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display rotation must be in 90 degree increments" +msgstr "Display rotation must be in 90 degree increments" + +#: shared-bindings/digitalio/DigitalInOut.c +msgid "Drive mode not used when direction is input." +msgstr "Drive mode not used when direction is input." + +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" +msgstr "ECB only operates on 16 bytes at a time" + +#: ports/esp32s2/common-hal/busio/SPI.c ports/esp32s2/common-hal/canio/CAN.c +msgid "ESP-IDF memory allocation failed" +msgstr "ESP-IDF memory allocation failed" + +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +msgid "EXTINT channel already in use" +msgstr "EXTINT channel already in use" + +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + +#: extmod/modure.c +msgid "Error in regex" +msgstr "Error in regex" + +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "Error: Failure to bind" +msgstr "Error: Failure to bind" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c py/enum.c +#: shared-bindings/_bleio/__init__.c shared-bindings/aesio/aes.c +#: shared-bindings/busio/SPI.c shared-bindings/microcontroller/Pin.c +#: shared-bindings/neopixel_write/__init__.c +#: shared-bindings/terminalio/Terminal.c +msgid "Expected a %q" +msgstr "Expected a %q" + +#: shared-bindings/_bleio/CharacteristicBuffer.c +#: shared-bindings/_bleio/Descriptor.c shared-bindings/_bleio/PacketBuffer.c +msgid "Expected a Characteristic" +msgstr "Expected a Characteristic" + +#: shared-bindings/_bleio/Adapter.c +msgid "Expected a DigitalInOut" +msgstr "Expected a DigitalInOut" + +#: shared-bindings/_bleio/Characteristic.c +msgid "Expected a Service" +msgstr "Expected a service" + +#: shared-bindings/_bleio/Adapter.c +msgid "Expected a UART" +msgstr "Expected a UART" + +#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c +#: shared-bindings/_bleio/Service.c +msgid "Expected a UUID" +msgstr "Expected a UUID" + +#: shared-bindings/_bleio/Adapter.c +msgid "Expected an Address" +msgstr "Expected an address" + +#: shared-bindings/alarm/__init__.c +msgid "Expected an alarm" +msgstr "Expected an alarm" + +#: shared-module/_pixelbuf/PixelBuf.c +#, c-format +msgid "Expected tuple of length %d, got %d" +msgstr "Expected tuple of length %d, got %d" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "Extended advertisements with scan response not supported." +msgstr "Extended advertisements with scan response not supported." + +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" +msgstr "FFT is defined for ndarrays only" + +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" +msgstr "FFT is implemented for linear arrays only" + +#: ports/esp32s2/common-hal/ssl/SSLSocket.c +msgid "Failed SSL handshake" +msgstr "Failed SSL handshake" + +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." +msgstr "Failed sending command." + +#: ports/nrf/sd_mutex.c +#, c-format +msgid "Failed to acquire mutex, err 0x%04x" +msgstr "Failed to acquire mutex, err 0x%04x" + +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "Failed to allocate RX buffer" +msgstr "Failed to allocate RX buffer" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/esp32s2/common-hal/pulseio/PulseIn.c +#: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c +#: ports/stm/common-hal/pulseio/PulseIn.c +#, c-format +msgid "Failed to allocate RX buffer of %d bytes" +msgstr "Failed to allocate RX buffer of %d bytes" + +#: ports/esp32s2/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" +msgstr "Failed to allocate WiFi memory" + +#: ports/esp32s2/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" +msgstr "Failed to allocate WiFi scan memory" + +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" +msgstr "Failed to connect: internal error" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" +msgstr "Failed to connect: timeout" + +#: ports/esp32s2/common-hal/wifi/__init__.c +msgid "Failed to init wifi" +msgstr "Failed to init WiFi" + +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" +msgstr "Failed to parse MP3 file" + +#: ports/nrf/sd_mutex.c +#, c-format +msgid "Failed to release mutex, err 0x%04x" +msgstr "Failed to release mutex, err 0x%04x" + +#: supervisor/shared/safe_mode.c +msgid "Failed to write internal flash." +msgstr "Failed to write internal flash." + +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + +#: py/moduerrno.c +msgid "File exists" +msgstr "File exists" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/esp32s2/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" +msgstr "Filters too complex" + +#: ports/esp32s2/common-hal/dualbank/__init__.c +msgid "Firmware image is invalid" +msgstr "Firmware image is invalid" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Format not supported" +msgstr "Format not supported" + +#: shared-module/framebufferio/FramebufferDisplay.c +#, c-format +msgid "Framebuffer requires %d bytes" +msgstr "Framebuffer requires %d bytes" + +#: shared-bindings/pwmio/PWMOut.c +msgid "Frequency must match existing PWMOut using this timer" +msgstr "Frequency must match existing PWMOut using this timer" + +#: shared-bindings/bitbangio/I2C.c shared-bindings/bitbangio/SPI.c +#: shared-bindings/busio/I2C.c shared-bindings/busio/SPI.c +msgid "Function requires lock" +msgstr "Function requires lock" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Generic Failure" +msgstr "Generic Failure" + +#: shared-bindings/displayio/Display.c +#: shared-bindings/displayio/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Group already used" +msgstr "Group already used" + +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c +#: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c +#: ports/stm/common-hal/sdioio/SDCard.c +msgid "Hardware busy, try alternative pins" +msgstr "Hardware busy, try alternative pins" + +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +msgid "Hardware in use, try alternative pins" +msgstr "Hardware in use, try alternative pins" + +#: shared-bindings/wifi/Radio.c +msgid "Hostname must be between 1 and 253 characters" +msgstr "Hostname must be between 1 and 253 characters" + +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "I/O operation on closed file" + +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C Init Error" +msgstr "I2C init error" + +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "I2C peripheral in use" +msgstr "I2C peripheral in use" + +#: shared-bindings/audiobusio/I2SOut.c +msgid "I2SOut not available" +msgstr "I2SOut not available" + +#: shared-bindings/aesio/aes.c +#, c-format +msgid "IV must be %d bytes long" +msgstr "IV must be %d bytes long" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "In-buffer elements must be <= 4 bytes long" + +#: py/persistentcode.c +msgid "" +"Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" +"mpy-update for more info." +msgstr "" +"Incompatible .mpy file. Please update all .mpy files. See https://adafru.it/" +"mpy-update for more info." + +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" +msgstr "Incorrect buffer size" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" +msgstr "Init program size invalid" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "Initial set pin direction conflicts with initial out pin direction" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "Initial set pin state conflicts with initial out pin state" + +#: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c +msgid "Initialization failed due to lack of memory" +msgstr "Initialisation failed due to lack of memory" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "Input buffer length (%d) must be a multiple of the strand count (%d)" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" +msgstr "Input taking too long" + +#: ports/esp32s2/common-hal/neopixel_write/__init__.c py/moduerrno.c +msgid "Input/output error" +msgstr "Input/output error" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Instruction %d jumps on pin" +msgstr "Instruction %d jumps on pin" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Instruction %d shifts in more bits than pin count" +msgstr "Instruction %d shifts in more bits than pin count" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Instruction %d shifts out more bits than pin count" +msgstr "Instruction %d shifts out more bits than pin count" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Instruction %d uses extra pin" +msgstr "Instruction %d uses extra pin" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Instruction %d waits on input outside of count" +msgstr "Instruction %d waits on input outside of count" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" +msgstr "Insufficient authentication" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" +msgstr "Insufficient encryption" + +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" +msgstr "Internal define error" + +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" +msgstr "Internal error #%d" + +#: shared-bindings/sdioio/SDCard.c +msgid "Invalid %q" +msgstr "Invalid %q" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Invalid %q pin" +msgstr "Invalid %q pin" + +#: ports/stm/common-hal/busio/I2C.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c ports/stm/common-hal/canio/CAN.c +#: ports/stm/common-hal/sdioio/SDCard.c +msgid "Invalid %q pin selection" +msgstr "Invalid %q pin selection" + +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" +msgstr "Invalid ADC unit value" + +#: shared-module/displayio/OnDiskBitmap.c +msgid "Invalid BMP file" +msgstr "Invalid BMP file" + +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" +msgstr "Invalid BSSID" + +#: ports/esp32s2/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +msgid "Invalid DAC pin supplied" +msgstr "Invalid DAC pin supplied" + +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + +#: ports/atmel-samd/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c +msgid "Invalid PWM frequency" +msgstr "Invalid PWM frequency" + +#: ports/esp32s2/common-hal/analogio/AnalogIn.c +msgid "Invalid Pin" +msgstr "Invalid pin" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +#: py/moduerrno.c shared-module/rgbmatrix/RGBMatrix.c +msgid "Invalid argument" +msgstr "Invalid argument" + +#: shared-module/displayio/Bitmap.c +msgid "Invalid bits per value" +msgstr "Invalid bits per value" + +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "Invalid buffer size" +msgstr "Invalid buffer size" + +#: shared-bindings/_pixelbuf/PixelBuf.c +msgid "Invalid byteorder string" +msgstr "Invalid byteorder string" + +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/esp32s2/common-hal/frequencyio/FrequencyIn.c +msgid "Invalid capture period. Valid range: 1 - 500" +msgstr "Invalid capture period. Valid range: 1 - 500" + +#: shared-bindings/audiomixer/Mixer.c +msgid "Invalid channel count" +msgstr "Invalid channel count" + +#: shared-bindings/digitalio/DigitalInOut.c +msgid "Invalid direction." +msgstr "Invalid direction." + +#: shared-module/audiocore/WaveFile.c +msgid "Invalid file" +msgstr "Invalid file" + +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" +msgstr "Invalid format chunk size" + +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c +msgid "Invalid frequency" +msgstr "Invalid frequency" + +#: supervisor/shared/safe_mode.c +msgid "Invalid memory access." +msgstr "Invalid memory access." + +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "Invalid number of bits" +msgstr "Invalid number of bits" + +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +#: shared-bindings/displayio/FourWire.c +msgid "Invalid phase" +msgstr "Invalid phase" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +#: ports/esp32s2/common-hal/alarm/touch/TouchAlarm.c +#: ports/esp32s2/common-hal/touchio/TouchIn.c shared-bindings/pwmio/PWMOut.c +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "Invalid pin" +msgstr "Invalid pin" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Invalid pin for left channel" +msgstr "Invalid pin for left channel" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Invalid pin for right channel" +msgstr "Invalid pin for right channel" + +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/atmel-samd/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/i2cperipheral/I2CPeripheral.c +#: ports/cxd56/common-hal/busio/I2C.c ports/cxd56/common-hal/busio/SPI.c +#: ports/cxd56/common-hal/busio/UART.c ports/cxd56/common-hal/sdioio/SDCard.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c +#: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "Invalid pins" +msgstr "Invalid pins" + +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +#: shared-bindings/displayio/FourWire.c +msgid "Invalid polarity" +msgstr "Invalid polarity" + +#: shared-bindings/_bleio/Characteristic.c +msgid "Invalid properties" +msgstr "Invalid properties" + +#: shared-bindings/microcontroller/__init__.c +msgid "Invalid run mode." +msgstr "Invalid run mode." + +#: shared-module/_bleio/Attribute.c +msgid "Invalid security_mode" +msgstr "Invalid security_mode" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Invalid size" +msgstr "Invalid size" + +#: ports/esp32s2/common-hal/ssl/SSLContext.c +msgid "Invalid socket for TLS" +msgstr "Invalid socket for TLS" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Invalid state" +msgstr "Invalid state" + +#: shared-bindings/audiomixer/Mixer.c +msgid "Invalid voice" +msgstr "Invalid voice" + +#: shared-bindings/audiomixer/Mixer.c +msgid "Invalid voice count" +msgstr "Invalid voice count" + +#: shared-module/audiocore/WaveFile.c +msgid "Invalid wave file" +msgstr "Invalid wave file" + +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +msgid "Invalid word/bit length" +msgstr "Invalid word/bit length" + +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" +msgstr "Key must be 16, 24, or 32 bytes long" + +#: py/compile.c +msgid "LHS of keyword arg must be an id" +msgstr "LHS of keyword arg must be an id" + +#: shared-module/displayio/Group.c +msgid "Layer already in a group." +msgstr "Layer already in a group." + +#: shared-module/displayio/Group.c +msgid "Layer must be a Group or TileGrid subclass." +msgstr "Layer must be a Group or TileGrid subclass." + +#: py/objslice.c +msgid "Length must be an int" +msgstr "Length must be an int" + +#: py/objslice.c +msgid "Length must be non-negative" +msgstr "Length must be non-negative" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "MAC address was invalid" +msgstr "MAC address was invalid" + +#: shared-module/bitbangio/SPI.c +msgid "MISO pin init failed." +msgstr "MISO pin init failed." + +#: shared-module/bitbangio/SPI.c +msgid "MOSI pin init failed." +msgstr "MOSI pin init failed." + +#: shared-module/displayio/Shape.c +#, c-format +msgid "Maximum x value when mirrored is %d" +msgstr "Maximum x value when mirrored is %d" + +#: shared-bindings/canio/Message.c +msgid "Messages limited to 8 bytes" +msgstr "Messages limited to 8 bytes" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "Microphone startup delay must be in range 0.0 to 1.0" +msgstr "Microphone startup delay must be in range 0.0 to 1.0" + +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/SPI.c +msgid "Missing MISO or MOSI Pin" +msgstr "Missing MISO or MOSI pin" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Missing first_in_pin. Instruction %d reads pin(s)" +msgstr "Missing first_in_pin. Instruction %d reads pin(s)" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Missing first_in_pin. Instruction %d shifts in from pin(s)" +msgstr "Missing first_in_pin. Instruction %d shifts in from pin(s)" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Missing first_in_pin. Instruction %d waits based on pin" +msgstr "Missing first_in_pin. Instruction %d waits based on pin" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Missing first_out_pin. Instruction %d shifts out to pin(s)" +msgstr "Missing first_out_pin. Instruction %d shifts out to pin(s)" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Missing first_out_pin. Instruction %d writes pin(s)" +msgstr "Missing first_out_pin. Instruction %d writes pin(s)" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Missing first_set_pin. Instruction %d sets pin(s)" +msgstr "Missing first_set_pin. Instruction %d sets pin(s)" + +#: shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." +msgstr "Must be a %q subclass." + +#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" +msgstr "Must provide MISO or MOSI pin" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Must use a multiple of 6 rgb pins, not %d" +msgstr "Must use a multiple of 6 rgb pins, not %d" + +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + +#: ports/esp32s2/common-hal/nvm/ByteArray.c +msgid "NVS Error" +msgstr "NVS Error" + +#: py/parse.c +msgid "Name too long" +msgstr "Name too long" + +#: ports/nrf/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" +msgstr "No CCCD for this Characteristic" + +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +msgid "No DAC on chip" +msgstr "No DAC on chip" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA channel found" +msgstr "No DMA channel found" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "No DMA pacing timer found" + +#: shared-module/adafruit_bus_device/I2CDevice.c +#, c-format +msgid "No I2C device at address: %x" +msgstr "No I2C device at address: %x" + +#: ports/esp32s2/common-hal/busio/SPI.c ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/SPI.c +msgid "No MISO Pin" +msgstr "No MISO pin" + +#: ports/esp32s2/common-hal/busio/SPI.c ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/SPI.c +msgid "No MOSI Pin" +msgstr "No MOSI pin" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/esp32s2/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +msgid "No RX pin" +msgstr "No RX pin" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/esp32s2/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +msgid "No TX pin" +msgstr "No TX pin" + +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +msgid "No available clocks" +msgstr "No available clocks" + +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" +msgstr "No connection: length cannot be determined" + +#: shared-bindings/board/__init__.c +msgid "No default %q bus" +msgstr "No default %q bus" + +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" +msgstr "No free GCLKs" + +#: shared-bindings/os/__init__.c +msgid "No hardware random available" +msgstr "No hardware random available" + +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +msgid "No hardware support on clk pin" +msgstr "No hardware support on clk pin" + +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "No hardware support on pin" +msgstr "No hardware support on pin" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "No in in program" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "No in or out in program" + +#: shared-bindings/aesio/aes.c +msgid "No key was specified" +msgstr "No key was specified" + +#: shared-bindings/time/__init__.c +msgid "No long integer support" +msgstr "No long integer support" + +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" +msgstr "No network with that ssid" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No out in program" +msgstr "No out in program" + +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "No pull up found on SDA or SCL; check your wiring" + +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" +msgstr "No pulldown on pin; 1Mohm recommended" + +#: py/moduerrno.c +msgid "No space left on device" +msgstr "No space left on device" + +#: py/moduerrno.c +msgid "No such file/directory" +msgstr "No such file/directory" + +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" +msgstr "No timer available" + +#: supervisor/shared/safe_mode.c +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "" + +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" +msgstr "Not a valid IP string" + +#: ports/nrf/common-hal/_bleio/PacketBuffer.c +#: ports/nrf/common-hal/_bleio/__init__.c +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "Not connected" +msgstr "Not connected" + +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c +msgid "Not playing" +msgstr "Not playing" + +#: main.c +msgid "Not running saved code.\n" +msgstr "Not running saved code.\n" + +#: shared-bindings/_bleio/__init__.c +msgid "Not settable" +msgstr "Not settable" + +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." +msgstr "" +"Object has been deinitialised and can no longer be used. Create a new object." + +#: ports/nrf/common-hal/busio/UART.c +msgid "Odd parity is not supported" +msgstr "Odd parity is not supported" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "Only 8 or 16 bit mono with " +msgstr "Only 8 or 16 bit mono with " + +#: ports/esp32s2/common-hal/wifi/__init__.c +msgid "Only IPv4 addresses supported" +msgstr "Only IPv4 addresses supported" + +#: ports/esp32s2/common-hal/socketpool/SocketPool.c +msgid "Only IPv4 sockets supported" +msgstr "Only IPv4 sockets supported" + +#: shared-module/displayio/OnDiskBitmap.c +#, c-format +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" +msgstr "" +"Only Windows format, uncompressed BMP supported: given header size is %d" + +#: shared-module/displayio/OnDiskBitmap.c +#, c-format +msgid "" +"Only monochrome, indexed 4bpp or 8bpp, and 16bpp or greater BMPs supported: " +"%d bpp given" +msgstr "" +"Only monochrome, indexed 4bpp or 8bpp, and 16bpp or greater BMPs supported: " +"%d bpp given" + +#: ports/esp32s2/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one TouchAlarm can be set in deep sleep." +msgstr "Only one TouchAlarm can be set in deep sleep." + +#: ports/esp32s2/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." +msgstr "Only one alarm.time alarm can be set." + +#: shared-module/displayio/ColorConverter.c +msgid "Only one color can be transparent at a time" +msgstr "Only one colour can be transparent at a time" + +#: shared-bindings/ipaddress/__init__.c +msgid "Only raw int supported for ip" +msgstr "Only raw int supported for ip" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Operation or feature not supported" +msgstr "Operation or feature not supported" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Operation timed out" +msgstr "Operation timed out" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Out of memory" +msgstr "Out of memory" + +#: ports/esp32s2/common-hal/socketpool/SocketPool.c +msgid "Out of sockets" +msgstr "Out of sockets" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "Out-buffer elements must be <= 4 bytes long" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "Output buffer must be at least %d bytes" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "Oversample must be multiple of 8." +msgstr "Oversample must be multiple of 8." + +#: shared-bindings/audiobusio/PDMIn.c +msgid "PDMIn not available" +msgstr "PDMIn not available" + +#: shared-bindings/pwmio/PWMOut.c +msgid "" +"PWM duty_cycle must be between 0 and 65535 inclusive (16 bit resolution)" +msgstr "" +"PWM duty_cycle must be between 0 and 65535 inclusive (16 bit resolution)" + +#: shared-bindings/pwmio/PWMOut.c +msgid "" +"PWM frequency not writable when variable_frequency is False on construction." +msgstr "" +"PWM frequency not writable when variable_frequency is False on construction." + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "PWM slice already in use" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "PWM slice channel A already in use" + +#: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c +#: ports/stm/common-hal/displayio/ParallelBus.c +msgid "ParallelBus not yet supported" +msgstr "ParallelBus not yet supported" + +#: ports/esp32s2/common-hal/audiobusio/__init__.c +msgid "Peripheral in use" +msgstr "Peripheral in use" + +#: py/moduerrno.c +msgid "Permission denied" +msgstr "Permission denied" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Pin count must be at least 1" +msgstr "Pin count must be at least 1" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Pin count too large" +msgstr "Pin count too large" + +#: ports/atmel-samd/common-hal/analogio/AnalogIn.c +#: ports/cxd56/common-hal/analogio/AnalogIn.c +#: ports/esp32s2/common-hal/analogio/AnalogIn.c +#: ports/mimxrt10xx/common-hal/analogio/AnalogIn.c +#: ports/nrf/common-hal/analogio/AnalogIn.c +#: ports/raspberrypi/common-hal/analogio/AnalogIn.c +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Pin does not have ADC capabilities" +msgstr "Pin does not have ADC capabilities" + +#: shared-bindings/adafruit_bus_device/SPIDevice.c +#: shared-bindings/digitalio/DigitalInOut.c +msgid "Pin is input only" +msgstr "Pin is input only" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "Pin must be on PWM Channel B" + +#: ports/atmel-samd/common-hal/countio/Counter.c +msgid "Pin must support hardware interrupts" +msgstr "Pin must support hardware interrupts" + +#: ports/stm/common-hal/pulseio/PulseIn.c +msgid "Pin number already reserved by EXTI" +msgstr "Pin number already reserved by EXTI" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "" +"Pinout uses %d bytes per element, which consumes more than the ideal %d " +"bytes. If this cannot be avoided, pass allow_inefficient=True to the " +"constructor" +msgstr "" +"Pinout uses %d bytes per element, which consumes more than the ideal %d " +"bytes. If this cannot be avoided, pass allow_inefficient=True to the " +"constructor" + +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "Pins must be sequential" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "Pins must share PWM slice" + +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" +msgstr "Plus any modules on the filesystem\n" + +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" +msgstr "Polygon needs at least 3 points" + +#: ports/esp32s2/common-hal/pulseio/PulseOut.c +msgid "" +"Port does not accept PWM carrier. Pass a pin, frequency and duty cycle " +"instead" +msgstr "" +"Port does not accept PWM carrier. Pass a pin, frequency and duty cycle " +"instead" + +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +#: ports/nrf/common-hal/pulseio/PulseOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "" +"Port does not accept pins or frequency. Construct and pass a PWMOut Carrier " +"instead" +msgstr "" +"Port does not accept pins or frequency. Construct and pass a PWMOut Carrier " +"instead" + +#: shared-bindings/_bleio/Adapter.c +msgid "Prefix buffer must be on the heap" +msgstr "Prefix buffer must be on the heap" + +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +msgstr "Press any key to enter the REPL. Use CTRL-D to reload.\n" + +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "Pretending to deep sleep until alarm, CTRL-C or file write.\n" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does IN without loading ISR" +msgstr "Program does IN without loading ISR" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does OUT without loading OSR" +msgstr "Program does OUT without loading OSR" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program must contain at least one 16-bit instruction." +msgstr "Program must contain at least one 16-bit instruction." + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" +msgstr "Program size invalid" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program too large" +msgstr "Program too large" + +#: shared-bindings/digitalio/DigitalInOut.c +msgid "Pull not used when direction is output." +msgstr "Pull not used when direction is output." + +#: ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c +msgid "RAISE mode is not implemented" +msgstr "RAISE mode is not implemented" + +#: ports/stm/common-hal/os/__init__.c +msgid "RNG DeInit Error" +msgstr "RNG deinit Error" + +#: ports/stm/common-hal/os/__init__.c +msgid "RNG Init Error" +msgstr "RNG init Error" + +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "RS485 not yet supported on this device" + +#: ports/esp32s2/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" +msgstr "RS485 inversion specified when not in RS485 mode" + +#: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c +#: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c +msgid "RTC calibration is not supported on this board" +msgstr "RTC calibration is not supported on this board" + +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" +msgstr "RTC is not supported on this board" + +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "RTS/CTS/RS485 Not yet supported on this device" +msgstr "RTS/CTS/RS485 not yet supported on this device" + +#: ports/stm/common-hal/os/__init__.c +msgid "Random number generation error" +msgstr "Random number generation error" + +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Read-only" +msgstr "Read-only" + +#: extmod/vfs_fat.c py/moduerrno.c +msgid "Read-only filesystem" +msgstr "Read-only filesystem" + +#: shared-module/displayio/Bitmap.c +msgid "Read-only object" +msgstr "Read-only object" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Received response was invalid" +msgstr "Received response was invalid" + +#: shared-bindings/displayio/EPaperDisplay.c +msgid "Refresh too soon" +msgstr "Refresh too soon" + +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" +msgstr "RemoteTransmissionRequests limited to 8 bytes" + +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" +msgstr "Requested AES mode is unsupported" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Requested resource not found" +msgstr "Requested resource not found" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" +msgstr "Right channel unsupported" + +#: shared-bindings/_pew/PewPew.c +msgid "Row entry must be digitalio.DigitalInOut" +msgstr "Row entry must be digitalio. DigitalInOut" + +#: main.c +msgid "Running in safe mode! " +msgstr "Running in safe mode! " + +#: shared-module/sdcardio/SDCard.c +msgid "SD card CSD format not supported" +msgstr "SD card CSD format not supported" + +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" +msgstr "SDIO GetCardInfo error %d" + +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO Init Error %d" +msgstr "SDIO init error %d" + +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI Init Error" +msgstr "SPI init error" + +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI Re-initialization error" +msgstr "SPI reinitialisation error" + +#: ports/raspberrypi/common-hal/busio/SPI.c +msgid "SPI peripheral in use" +msgstr "SPI peripheral in use" + +#: shared-bindings/audiomixer/Mixer.c +msgid "Sample rate must be positive" +msgstr "Sample rate must be positive" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#, c-format +msgid "Sample rate too high. It must be less than %d" +msgstr "Sample rate too high. It must be less than %d" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "Scan already in progess. Stop with stop_scan." +msgstr "Scan already in progess. Stop with stop_scan." + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" +msgstr "Serialiser in use" + +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" +msgstr "Server side context cannot have hostname" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Set pin count must be between 1 and 5" +msgstr "Set pin count must be between 1 and 5" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Side set pin count must be between 1 and 5" +msgstr "Side set pin count must be between 1 and 5" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" +msgstr "Size not supported" + +#: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." +msgstr "Slice and value different lengths." + +#: shared-bindings/displayio/Bitmap.c shared-bindings/displayio/Group.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Slices not supported" +msgstr "Slices not supported" + +#: ports/esp32s2/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" +msgstr "SocketPool can only be used with wifi.radio" + +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" +msgstr "Source and destination buffers must be the same length" + +#: extmod/modure.c +msgid "Splitting with sub-captures" +msgstr "Splitting with sub-captures" + +#: shared-bindings/supervisor/__init__.c +msgid "Stack size must be at least 256" +msgstr "Stack size must be at least 256" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "Stereo left must be on PWM channel A" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "Stereo right must be on PWM channel B" + +#: shared-bindings/multiterminal/__init__.c +msgid "Stream missing readinto() or write() method." +msgstr "Stream missing readinto() or write() method." + +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +msgid "Supply at least one UART pin" +msgstr "Supply at least one UART pin" + +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" +msgstr "Supply one of monotonic_time or epoch_time" + +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" +msgstr "System entry must be gnss.SatelliteSystem" + +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" +msgstr "Temperature read timed out" + +#: supervisor/shared/safe_mode.c +msgid "" +"The CircuitPython heap was corrupted because the stack was too small.\n" +"Please increase the stack size if you know how, or if not:" +msgstr "" +"The CircuitPython heap was corrupted because the stack was too small.\n" +"Please increase the stack size if you know how, or if not:" + +#: supervisor/shared/safe_mode.c +msgid "" +"The `microcontroller` module was used to boot into safe mode. Press reset to " +"exit safe mode.\n" +msgstr "" +"The `microcontroller` module was used to boot into safe mode. Press reset to " +"exit safe mode.\n" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +msgstr "The length of rgb_pins must be 6, 12, 18, 24, or 30" + +#: supervisor/shared/safe_mode.c +msgid "" +"The microcontroller's power dipped. Make sure your power supply provides\n" +"enough power for the whole circuit and press reset (after ejecting " +"CIRCUITPY).\n" +msgstr "" +"The microcontroller's power dipped. Make sure your power supply provides\n" +"enough power for the whole circuit and press reset (after ejecting " +"CIRCUITPY).\n" + +#: shared-module/audiomixer/MixerVoice.c +msgid "The sample's bits_per_sample does not match the mixer's" +msgstr "The sample's bits_per_sample does not match the mixer's" + +#: shared-module/audiomixer/MixerVoice.c +msgid "The sample's channel count does not match the mixer's" +msgstr "The sample's channel count does not match the mixer's" + +#: shared-module/audiomixer/MixerVoice.c +msgid "The sample's sample rate does not match the mixer's" +msgstr "The sample's sample rate does not match the mixer's" + +#: shared-module/audiomixer/MixerVoice.c +msgid "The sample's signedness does not match the mixer's" +msgstr "The sample's signedness does not match the mixer's" + +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" +msgstr "Tile height must exactly divide bitmap height" + +#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +msgid "Tile index out of bounds" +msgstr "Tile index out of bounds" + +#: shared-bindings/displayio/TileGrid.c +msgid "Tile value out of bounds" +msgstr "Tile value out of bounds" + +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" +msgstr "Tile width must exactly divide bitmap width" + +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." +msgstr "Time is in the past." + +#: ports/nrf/common-hal/_bleio/Adapter.c +#, c-format +msgid "Timeout is too long: Maximum timeout length is %d seconds" +msgstr "Timeout is too long: Maximum timeout length is %d seconds" + +#: supervisor/shared/safe_mode.c +msgid "To exit, please reset the board without " +msgstr "To exit, please reset the board without " + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample." +msgstr "Too many channels in sample." + +#: shared-module/displayio/__init__.c +msgid "Too many display busses" +msgstr "Too many display busses" + +#: shared-module/displayio/__init__.c +msgid "Too many displays" +msgstr "Too many displays" + +#: ports/nrf/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" +msgstr "" + +#: py/obj.c +msgid "Traceback (most recent call last):\n" +msgstr "Traceback (most recent call last):\n" + +#: shared-bindings/time/__init__.c +msgid "Tuple or struct_time argument required" +msgstr "Tuple or struct_time argument required" + +#: ports/stm/common-hal/busio/UART.c +msgid "UART Buffer allocation error" +msgstr "UART buffer allocation error" + +#: ports/stm/common-hal/busio/UART.c +msgid "UART De-init error" +msgstr "UART deinit error" + +#: ports/stm/common-hal/busio/UART.c +msgid "UART Init Error" +msgstr "UART init Error" + +#: ports/stm/common-hal/busio/UART.c +msgid "UART Re-init error" +msgstr "UART reinit error" + +#: ports/stm/common-hal/busio/UART.c +msgid "UART write error" +msgstr "UART write error" + +#: shared-module/usb_hid/Device.c +msgid "USB Busy" +msgstr "USB busy" + +#: shared-module/usb_hid/Device.c +msgid "USB Error" +msgstr "USB error" + +#: shared-bindings/_bleio/UUID.c +msgid "UUID integer value must be 0-0xffff" +msgstr "UUID integer value must be 0-0xffff" + +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +msgstr "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" + +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" +msgstr "UUID value is not str, int or byte buffer" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Unable to allocate buffers for signed conversion" +msgstr "Unable to allocate buffers for signed conversion" + +#: ports/esp32s2/common-hal/busio/I2C.c +msgid "Unable to create lock" +msgstr "Unable to create lock" + +#: shared-module/displayio/I2CDisplay.c +#, c-format +msgid "Unable to find I2C Display at %x" +msgstr "Unable to find I2C display at %x" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Unable to find free GCLK" +msgstr "Unable to find free GCLK" + +#: py/parse.c +msgid "Unable to init parser" +msgstr "Unable to init parser" + +#: shared-module/displayio/OnDiskBitmap.c +msgid "Unable to read color palette data" +msgstr "Unable to read colour palette data" + +#: shared-bindings/nvm/ByteArray.c +msgid "Unable to write to nvm." +msgstr "Unable to write to nvm." + +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." +msgstr "Unable to write to sleep_memory." + +#: ports/nrf/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" +msgstr "Unexpected nrfx uuid type" + +#: ports/esp32s2/common-hal/ssl/SSLSocket.c +#, c-format +msgid "Unhandled ESP TLS error %d %d %x %d" +msgstr "Unhandled ESP TLS error %d %d %x %d" + +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" +msgstr "Unknown failure %d" + +#: ports/nrf/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" +msgstr "Unknown gatt error: 0x%04x" + +#: supervisor/shared/safe_mode.c +msgid "Unknown reason." +msgstr "Unknown reason." + +#: ports/nrf/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown security error: 0x%04x" +msgstr "Unknown security error: 0x%04x" + +#: ports/nrf/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown system firmware error: %04x" +msgstr "" + +#: shared-bindings/_pixelbuf/PixelBuf.c +#, c-format +msgid "Unmatched number of items on RHS (expected %d, got %d)." +msgstr "Unmatched number of items on RHS (expected %d, got %d)." + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "" +"Unspecified issue. Can be that the pairing prompt on the other device was " +"declined or ignored." +msgstr "" +"Unspecified issue. Can be that the pairing prompt on the other device was " +"declined or ignored." + +#: ports/atmel-samd/common-hal/busio/I2C.c ports/cxd56/common-hal/busio/I2C.c +#: ports/esp32s2/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/I2C.c ports/stm/common-hal/busio/I2C.c +msgid "Unsupported baudrate" +msgstr "Unsupported baudrate" + +#: shared-module/displayio/display_core.c +msgid "Unsupported display bus type" +msgstr "Unsupported display bus type" + +#: shared-module/audiocore/WaveFile.c +msgid "Unsupported format" +msgstr "Unsupported format" + +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c +msgid "Unsupported operation" +msgstr "Unsupported operation" + +#: shared-bindings/digitalio/DigitalInOut.c +msgid "Unsupported pull value." +msgstr "Unsupported pull value." + +#: ports/esp32s2/common-hal/dualbank/__init__.c +msgid "Update Failed" +msgstr "Update failed" + +#: ports/nrf/common-hal/_bleio/Characteristic.c +#: ports/nrf/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" +msgstr "Value length != required fixed length" + +#: ports/nrf/common-hal/_bleio/Characteristic.c +#: ports/nrf/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" +msgstr "Value length > max_length" + +#: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c +msgid "Version was invalid" +msgstr "Version was invalid" + +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" +msgstr "Voltage read timed out" + +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "WARNING: Your code filename has two extensions\n" + +#: ports/nrf/common-hal/watchdog/WatchDogTimer.c +#: ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +msgstr "WatchDogTimer cannot be deinitialised once mode is set to RESET" + +#: shared-bindings/watchdog/WatchDogTimer.c +msgid "WatchDogTimer is not currently running" +msgstr "WatchDogTimer is not currently running" + +#: shared-bindings/watchdog/WatchDogTimer.c +msgid "WatchDogTimer.mode cannot be changed once set to WatchDogMode.RESET" +msgstr "WatchDogTimer.mode cannot be changed once set to WatchDogMode.RESET" + +#: shared-bindings/watchdog/WatchDogTimer.c +msgid "WatchDogTimer.timeout must be greater than 0" +msgstr "WatchDogTimer.timeout must be greater than 0" + +#: supervisor/shared/safe_mode.c +msgid "Watchdog timer expired." +msgstr "WatchDog timer expired." + +#: py/builtinhelp.c +#, c-format +msgid "" +"Welcome to Adafruit CircuitPython %s!\n" +"\n" +"Please visit learn.adafruit.com/category/circuitpython for project guides.\n" +"\n" +"To list built-in modules please do `help(\"modules\")`.\n" +msgstr "" +"Welcome to Adafruit CircuitPython %s!\n" +"\n" +"Please visit learn.adafruit.com/category/circuitpython for project guides.\n" +"\n" +"To list built-in modules please do `help(\"modules\")`.\n" + +#: shared-bindings/wifi/Radio.c +msgid "WiFi password must be between 8 and 63 characters" +msgstr "WiFi password must be between 8 and 63 characters" + +#: main.c +msgid "Woken up by alarm.\n" +msgstr "Woken up by alarm.\n" + +#: ports/nrf/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" +msgstr "Writes not supported on Characteristic" + +#: supervisor/shared/safe_mode.c +msgid "You are in safe mode: something unanticipated happened.\n" +msgstr "You are in safe mode: something unanticipated happened.\n" + +#: supervisor/shared/safe_mode.c +msgid "You requested starting safe mode by " +msgstr "You requested starting safe mode by " + +#: py/objtype.c +msgid "__init__() should return None" +msgstr "__init__() should return None" + +#: py/objtype.c +msgid "__init__() should return None, not '%q'" +msgstr "__init__() should return None, not '%q'" + +#: py/objobject.c +msgid "__new__ arg must be a user-type" +msgstr "__new__ arg must be a user-type" + +#: extmod/modubinascii.c extmod/moduhashlib.c py/objarray.c +msgid "a bytes-like object is required" +msgstr "a bytes-like object is required" + +#: lib/embed/abort_.c +msgid "abort() called" +msgstr "abort() called" + +#: shared-bindings/i2cperipheral/I2CPeripheral.c +msgid "address out of bounds" +msgstr "address out of bounds" + +#: shared-bindings/i2cperipheral/I2CPeripheral.c +msgid "addresses is empty" +msgstr "addresses is empty" + +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + +#: py/modbuiltins.c +msgid "arg is an empty sequence" +msgstr "arg is an empty sequence" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "argsort argument must be an ndarray" +msgstr "argsort argument must be an ndarray" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "argsort is not implemented for flattened arrays" +msgstr "argsort is not implemented for flattened arrays" + +#: py/runtime.c +msgid "argument has wrong type" +msgstr "argument has wrong type" + +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c +msgid "argument num/types mismatch" +msgstr "argument num/types mismatch" + +#: py/runtime.c +msgid "argument should be a '%q' not a '%q'" +msgstr "argument should be a '%q' not a '%q'" + +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c +msgid "arguments must be ndarrays" +msgstr "arguments must be ndarrays" + +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" +msgstr "array and index length must be equal" + +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" +msgstr "array/bytes required on right side" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" +msgstr "attempt to get (arg)min/(arg)max of empty sequence" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" +msgstr "attempt to get argmin/argmax of an empty sequence" + +#: py/objstr.c +msgid "attributes not supported yet" +msgstr "attributes not supported yet" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "axis is out of bounds" +msgstr "axis is out of bounds" + +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" +msgstr "axis must be None, or an integer" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "axis too long" +msgstr "axis too long" + +#: py/builtinevex.c +msgid "bad compile mode" +msgstr "bad compile mode" + +#: py/objstr.c +msgid "bad conversion specifier" +msgstr "bad conversion specifier" + +#: py/objstr.c +msgid "bad format string" +msgstr "bad format string" + +#: py/binary.c py/objarray.c +msgid "bad typecode" +msgstr "bad typecode" + +#: py/emitnative.c +msgid "binary op %q not implemented" +msgstr "binary op %q not implemented" + +#: shared-bindings/busio/UART.c +msgid "bits must be in range 5 to 9" +msgstr "bits must be in range 5 to 9" + +#: shared-bindings/audiomixer/Mixer.c +msgid "bits_per_sample must be 8 or 16" +msgstr "bits_per_sample must be 8 or 16" + +#: py/emitinlinethumb.c +msgid "branch not in range" +msgstr "Branch not in range" + +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" +msgstr "Buffer is smaller than requested size" + +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" +msgstr "Buffer size must be a multiple of element size" + +#: shared-module/struct/__init__.c +msgid "buffer size must match format" +msgstr "Buffer size must match format" + +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" +msgstr "Buffer slices must be of equal length" + +#: py/modstruct.c shared-bindings/struct/__init__.c +#: shared-module/struct/__init__.c +msgid "buffer too small" +msgstr "Buffer too small" + +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" +msgstr "Buffer too small for requested bytes" + +#: shared-bindings/_pew/PewPew.c +msgid "buttons must be digitalio.DigitalInOut" +msgstr "Buttons must be digitalio.DigitalInOut" + +#: py/vm.c +msgid "byte code not implemented" +msgstr "Byte code not implemented" + +#: shared-bindings/_pixelbuf/PixelBuf.c +msgid "byteorder is not a string" +msgstr "Byteorder is not a string" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/esp32s2/common-hal/busio/UART.c +msgid "bytes > 8 bits not supported" +msgstr "Bytes > 8 bits not supported" + +#: py/objarray.c +msgid "bytes length not a multiple of item size" +msgstr "Bytes length not a multiple of item size" + +#: py/objstr.c +msgid "bytes value out of range" +msgstr "Bytes value out of range" + +#: ports/atmel-samd/bindings/samd/Clock.c ports/atmel-samd/common-hal/rtc/RTC.c +msgid "calibration is out of range" +msgstr "Calibration is out of range" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" +msgstr "Calibration is read only" + +#: ports/atmel-samd/common-hal/rtc/RTC.c +msgid "calibration value out of range +/-127" +msgstr "Calibration value out of range +/-127" + +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" +msgstr "Can only have up to 4 parameters to thumb assembly" + +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" +msgstr "Can only have up to 4 parameters to xtensa assembly" + +#: py/persistentcode.c +msgid "can only save bytecode" +msgstr "Can only save bytecode" + +#: py/objtype.c +msgid "can't add special method to already-subclassed class" +msgstr "Can't add special method to already-subclassed class" + +#: py/compile.c +msgid "can't assign to expression" +msgstr "Can't assign to expression" + +#: py/obj.c py/objint.c shared-bindings/i2cperipheral/I2CPeripheral.c +#: shared-module/_pixelbuf/PixelBuf.c +msgid "can't convert %q to %q" +msgstr "Can't convert %q to %q" + +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" +msgstr "Can't convert '%q' object to %q implicitly" + +#: py/obj.c +msgid "can't convert to %q" +msgstr "Can't convert to %q" + +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + +#: py/objstr.c +msgid "can't convert to str implicitly" +msgstr "Can't convert to str implicitly" + +#: py/compile.c +msgid "can't declare nonlocal in outer code" +msgstr "Can't declare nonlocal in outer code" + +#: py/compile.c +msgid "can't delete expression" +msgstr "Can't delete expression" + +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" +msgstr "Can't do binary op between '%q' and '%q'" + +#: py/objcomplex.c +msgid "can't do truncated division of a complex number" +msgstr "Can't do truncated division of a complex number" + +#: py/compile.c +msgid "can't have multiple **x" +msgstr "can't have multiple **x" + +#: py/compile.c +msgid "can't have multiple *x" +msgstr "can't have multiple *x" + +#: py/emitnative.c +msgid "can't implicitly convert '%q' to 'bool'" +msgstr "can't implicitly convert '%q' to 'bool'" + +#: py/emitnative.c +msgid "can't load from '%q'" +msgstr "can't load from '%q'" + +#: py/emitnative.c +msgid "can't load with '%q' index" +msgstr "can't load with '%q' index" + +#: py/objgenerator.c +msgid "can't pend throw to just-started generator" +msgstr "can't pend throw to just-started generator" + +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" +msgstr "can't send non-None value to a just-started generator" + +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" +msgstr "can't set 512 block size" + +#: py/objnamedtuple.c +msgid "can't set attribute" +msgstr "can't set attribute" + +#: py/emitnative.c +msgid "can't store '%q'" +msgstr "can't store '%q'" + +#: py/emitnative.c +msgid "can't store to '%q'" +msgstr "can't store to '%q'" + +#: py/emitnative.c +msgid "can't store with '%q' index" +msgstr "Can't store with '%q' index" + +#: py/objstr.c +msgid "" +"can't switch from automatic field numbering to manual field specification" +msgstr "" +"can't switch from automatic field numbering to manual field specification" + +#: py/objstr.c +msgid "" +"can't switch from manual field specification to automatic field numbering" +msgstr "" +"can't switch from manual field specification to automatic field numbering" + +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" +msgstr "can't cast output with casting rule" + +#: py/objtype.c +msgid "cannot create '%q' instances" +msgstr "can't create '%q' instances" + +#: py/objtype.c +msgid "cannot create instance" +msgstr "can't create instance" + +#: py/runtime.c +msgid "cannot import name %q" +msgstr "can't import name %q" + +#: py/builtinimport.c +msgid "cannot perform relative import" +msgstr "can't perform relative import" + +#: py/emitnative.c +msgid "casting" +msgstr "casting" + +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" +msgstr "chars buffer too small" + +#: py/modbuiltins.c +msgid "chr() arg not in range(0x110000)" +msgstr "chr() arg not in range(0x110000)" + +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" +msgstr "chr() arg not in range(256)" + +#: shared-module/vectorio/Circle.c +msgid "circle can only be registered in one parent" +msgstr "circle can only be registered in one parent" + +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "clip point must be (x,y) tuple" + +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" +msgstr "code outside range 0~127" + +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +msgstr "colour buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" + +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" +msgstr "colour buffer must be a buffer, tuple, list, or int" + +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +msgstr "colour buffer must be a bytearray or array of type 'b' or 'B'" + +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" +msgstr "colour must be between 0x000000 and 0xffffff" + +#: shared-bindings/displayio/ColorConverter.c +msgid "color should be an int" +msgstr "colour should be an int" + +#: py/objcomplex.c +msgid "complex division by zero" +msgstr "complex division by zero" + +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" +msgstr "complex values not supported" + +#: extmod/moduzlib.c +msgid "compression header" +msgstr "compression header" + +#: py/parse.c +msgid "constant must be an integer" +msgstr "constant must be an integer" + +#: py/emitnative.c +msgid "conversion to object" +msgstr "conversion to object" + +#: extmod/ulab/code/numpy/filter/filter.c +msgid "convolve arguments must be linear arrays" +msgstr "convolve arguments must be linear arrays" + +#: extmod/ulab/code/numpy/filter/filter.c +msgid "convolve arguments must be ndarrays" +msgstr "convolve arguments must be ndarrays" + +#: extmod/ulab/code/numpy/filter/filter.c +msgid "convolve arguments must not be empty" +msgstr "convolve arguments must not be empty" + +#: extmod/ulab/code/numpy/poly/poly.c +msgid "could not invert Vandermonde matrix" +msgstr "could not invert Vandermonde matrix" + +#: shared-module/sdcardio/SDCard.c +msgid "couldn't determine SD card version" +msgstr "couldn't determine SD card version" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "cross is defined for 1D arrays of length 3" +msgstr "cross is defined for 1D arrays of length 3" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" +msgstr "cata must be iterable" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" +msgstr "cata must be of equal length" + +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" +msgstr "cata type not understood" + +#: py/parsenum.c +msgid "decimal numbers not supported" +msgstr "cecimal numbers not supported" + +#: py/compile.c +msgid "default 'except' must be last" +msgstr "default 'except' must be last" + +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" +msgstr "default is not a function" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" +msgstr "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +msgstr "destination buffer must be an array of type 'H' for bit_depth = 16" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination_length must be an int >= 0" +msgstr "destination_length must be an int >= 0" + +#: py/objdict.c +msgid "dict update sequence has wrong length" +msgstr "dict update sequence has wrong length" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "diff argument must be an ndarray" +msgstr "diff argument must be an ndarray" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "differentiation order out of range" +msgstr "differentiation order out of range" + +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "dimensions do not match" + +#: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c +#: shared-bindings/math/__init__.c +msgid "division by zero" +msgstr "division by zero" + +#: py/objdeque.c +msgid "empty" +msgstr "empty" + +#: extmod/moduheapq.c extmod/modutimeq.c +msgid "empty heap" +msgstr "empty heap" + +#: py/objstr.c +msgid "empty separator" +msgstr "empty separator" + +#: shared-bindings/random/__init__.c +msgid "empty sequence" +msgstr "empty sequence" + +#: py/objstr.c +msgid "end of format while looking for conversion specifier" +msgstr "end of format while looking for conversion specifier" + +#: shared-bindings/displayio/Shape.c +msgid "end_x should be an int" +msgstr "end_x should be an int" + +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" +msgstr "epoch_time not supported on this board" + +#: ports/nrf/common-hal/busio/UART.c +#, c-format +msgid "error = 0x%08lX" +msgstr "error = 0x%08lX" + +#: py/runtime.c +msgid "exceptions must derive from BaseException" +msgstr "exceptions must derive from BaseException" + +#: shared-bindings/canio/CAN.c +msgid "expected '%q' but got '%q'" +msgstr "expected '%q' but got '%q'" + +#: shared-bindings/canio/CAN.c +msgid "expected '%q' or '%q' but got '%q'" +msgstr "expected '%q' or '%q' but got '%q'" + +#: py/objstr.c +msgid "expected ':' after format specifier" +msgstr "expected ':' after format specifier" + +#: py/obj.c +msgid "expected tuple/list" +msgstr "expected tuple/list" + +#: py/modthread.c +msgid "expecting a dict for keyword args" +msgstr "expecting a dict for keyword args" + +#: py/compile.c +msgid "expecting an assembler instruction" +msgstr "expecting an assembler instruction" + +#: py/compile.c +msgid "expecting just a value for set" +msgstr "expecting just a value for set" + +#: py/compile.c +msgid "expecting key:value for dict" +msgstr "expecting key:value for dict" + +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" +msgstr "ext_hook is not a function" + +#: py/argcheck.c +msgid "extra keyword arguments given" +msgstr "extra keyword arguments given" + +#: py/argcheck.c +msgid "extra positional arguments given" +msgstr "extra positional arguments given" + +#: py/parse.c +msgid "f-string expression part cannot include a '#'" +msgstr "f-string expression part cannot include a '#'" + +#: py/parse.c +msgid "f-string expression part cannot include a backslash" +msgstr "f-string expression part cannot include a backslash" + +#: py/parse.c +msgid "f-string: empty expression not allowed" +msgstr "f-string: empty expression not allowed" + +#: py/parse.c +msgid "f-string: expecting '}'" +msgstr "f-string: expecting '}'" + +#: py/parse.c +msgid "f-string: single '}' is not allowed" +msgstr "f-string: single '}' is not allowed" + +#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c +msgid "file must be a file opened in byte mode" +msgstr "file must be a file opened in byte mode" + +#: shared-bindings/storage/__init__.c +msgid "filesystem must provide mount method" +msgstr "filesystem must provide mount method" + +#: extmod/ulab/code/numpy/vector/vector.c +msgid "first argument must be a callable" +msgstr "first argument must be a callable" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" +msgstr "first argument must be a function" + +#: extmod/ulab/code/ulab_create.c +msgid "first argument must be a tuple of ndarrays" +msgstr "first argument must be a tuple of ndarrays" + +#: extmod/ulab/code/numpy/vector/vector.c +msgid "first argument must be an ndarray" +msgstr "first argument must be an ndarray" + +#: py/objtype.c +msgid "first argument to super() must be type" +msgstr "first argument to super() must be type" + +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" +msgstr "flattening order must be either 'C', or 'F'" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "flip argument must be an ndarray" +msgstr "flip argument must be an ndarray" + +#: py/objint.c +msgid "float too big" +msgstr "float too big" + +#: shared-bindings/_stage/Text.c +msgid "font must be 2048 bytes long" +msgstr "font must be 2048 bytes long" + +#: py/objstr.c +msgid "format requires a dict" +msgstr "format requires a dict" + +#: py/objdeque.c +msgid "full" +msgstr "full" + +#: py/argcheck.c +msgid "function doesn't take keyword arguments" +msgstr "" + +#: py/argcheck.c +#, c-format +msgid "function expected at most %d arguments, got %d" +msgstr "function expected at most %d arguments, got %d" + +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" +msgstr "function got multiple values for argument '%q'" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" +msgstr "function has the same sign at the ends of interval" + +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" +msgstr "function is defined for ndarrays only" + +#: py/argcheck.c +#, c-format +msgid "function missing %d required positional arguments" +msgstr "function missing %d required positional arguments" + +#: py/bc.c +msgid "function missing keyword-only argument" +msgstr "function missing keyword-only argument" + +#: py/bc.c +msgid "function missing required keyword argument '%q'" +msgstr "function missing required keyword argument '%q'" + +#: py/bc.c +#, c-format +msgid "function missing required positional argument #%d" +msgstr "function missing required positional argument #%d" + +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/time/__init__.c +#, c-format +msgid "function takes %d positional arguments but %d were given" +msgstr "function takes %d positional arguments but %d were given" + +#: shared-bindings/time/__init__.c +msgid "function takes exactly 9 arguments" +msgstr "function takes exactly 9 arguments" + +#: py/objgenerator.c +msgid "generator already executing" +msgstr "generator already executing" + +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" +msgstr "generator ignored GeneratorExit" + +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + +#: shared-bindings/_stage/Layer.c +msgid "graphic must be 2048 bytes long" +msgstr "graphic must be 2048 bytes long" + +#: extmod/moduheapq.c +msgid "heap must be a list" +msgstr "heap must be a list" + +#: py/compile.c +msgid "identifier redefined as global" +msgstr "identifier redefined as global" + +#: py/compile.c +msgid "identifier redefined as nonlocal" +msgstr "identifier redefined as nonlocal" + +#: py/objstr.c +msgid "incomplete format" +msgstr "incomplete format" + +#: py/objstr.c +msgid "incomplete format key" +msgstr "incomplete format key" + +#: extmod/modubinascii.c +msgid "incorrect padding" +msgstr "incorrect padding" + +#: extmod/ulab/code/ndarray.c +msgid "index is out of bounds" +msgstr "index is out of bounds" + +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c +#: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" +msgstr "index out of range" + +#: py/obj.c +msgid "indices must be integers" +msgstr "indices must be integers" + +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" +msgstr "indices must be integers, slices, or Boolean lists" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" +msgstr "initial values must be iterable" + +#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c +msgid "initial_value length is wrong" +msgstr "initial_value length is wrong" + +#: py/compile.c +msgid "inline assembler must be a function" +msgstr "inline assembler must be a function" + +#: extmod/ulab/code/ndarray.c +msgid "input and output shapes are not compatible" +msgstr "input and output shapes are not compatible" + +#: extmod/ulab/code/ulab_create.c +msgid "input argument must be an integer, a tuple, or a list" +msgstr "input argument must be an integer, a tuple, or a list" + +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "input array length must be power of 2" +msgstr "input array length must be power of 2" + +#: extmod/ulab/code/ulab_create.c +msgid "input arrays are not compatible" +msgstr "input arrays are not compatible" + +#: extmod/ulab/code/numpy/poly/poly.c +msgid "input data must be an iterable" +msgstr "input data must be an iterable" + +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" +msgstr "input matrix is asymmetric" + +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is singular" +msgstr "input matrix is singular" + +#: extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" +msgstr "input must be a dense ndarray" + +#: extmod/ulab/code/ulab_create.c +msgid "input must be a tensor of rank 2" +msgstr "input must be a tensor of rank 2" + +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/user/user.c +msgid "input must be an ndarray" +msgstr "input must be an ndarray" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" +msgstr "input must be one-dimensional" + +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" +msgstr "input must be square matrix" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "input must be tuple, list, range, or ndarray" +msgstr "input must be tuple, list, range, or ndarray" + +#: extmod/ulab/code/numpy/poly/poly.c +msgid "input vectors must be of equal length" +msgstr "input vectors must be of equal length" + +#: extmod/ulab/code/numpy/poly/poly.c +msgid "inputs are not iterable" +msgstr "inputs are not iterable" + +#: py/parsenum.c +msgid "int() arg 2 must be >= 2 and <= 36" +msgstr "int() arg 2 must be >= 2 and <= 36" + +#: py/objstr.c +msgid "integer required" +msgstr "integer required" + +#: extmod/ulab/code/numpy/approx/approx.c +msgid "interp is defined for 1D arrays of equal length" +msgstr "interp is defined for 1D arrays of equal length" + +#: shared-bindings/_bleio/Adapter.c +#, c-format +msgid "interval must be in range %s-%s" +msgstr "interval must be in range %s-%s" + +#: lib/netutils/netutils.c +msgid "invalid arguments" +msgstr "invalid arguments" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" + +#: extmod/modussl_axtls.c +msgid "invalid cert" +msgstr "invalid cert" + +#: py/compile.c +msgid "invalid decorator" +msgstr "" + +#: extmod/uos_dupterm.c +msgid "invalid dupterm index" +msgstr "invalid dupterm index" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "invalid element size %d for bits_per_pixel %d\n" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "invalid element_size %d, must be, 1, 2, or 4" + +#: extmod/modframebuf.c +msgid "invalid format" +msgstr "invalid format" + +#: py/objstr.c +msgid "invalid format specifier" +msgstr "invalid format specifier" + +#: shared-bindings/wifi/Radio.c +msgid "invalid hostname" +msgstr "invalid hostname" + +#: extmod/modussl_axtls.c +msgid "invalid key" +msgstr "invalid key" + +#: py/compile.c +#, fuzzy +msgid "invalid micropython decorator" +msgstr "invalid CircuitPython decorator" + +#: shared-bindings/random/__init__.c +msgid "invalid step" +msgstr "invalid step" + +#: py/compile.c py/parse.c +msgid "invalid syntax" +msgstr "invalid syntax" + +#: py/parsenum.c +msgid "invalid syntax for integer" +msgstr "invalid syntax for integer" + +#: py/parsenum.c +#, c-format +msgid "invalid syntax for integer with base %d" +msgstr "invalid syntax for integer with base %d" + +#: py/parsenum.c +msgid "invalid syntax for number" +msgstr "invalid syntax for number" + +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" +msgstr "issubclass() arg 1 must be a class" + +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" +msgstr "issubclass() arg 2 must be a class or a tuple of classes" + +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" +msgstr "iterations did not converge" + +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" +msgstr "join expects a list of str/bytes objects consistent with self object" + +#: py/argcheck.c +msgid "keyword argument(s) not yet implemented - use normal args instead" +msgstr "keyword argument(s) not yet implemented - use normal args instead" + +#: py/bc.c +msgid "keywords must be strings" +msgstr "keywords must be strings" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" +msgstr "label '%q' not defined" + +#: py/compile.c +msgid "label redefined" +msgstr "label redefined" + +#: py/stream.c +msgid "length argument not allowed for this type" +msgstr "length argument not allowed for this type" + +#: shared-bindings/audiomixer/MixerVoice.c +msgid "level must be between 0 and 1" +msgstr "level must be between 0 and 1" + +#: py/objarray.c +msgid "lhs and rhs should be compatible" +msgstr "lhs and rhs should be compatible" + +#: py/emitnative.c +msgid "local '%q' has type '%q' but source is '%q'" +msgstr "local '%q' has type '%q' but source is '%q'" + +#: py/emitnative.c +msgid "local '%q' used before type known" +msgstr "local '%q' used before type known" + +#: py/vm.c +msgid "local variable referenced before assignment" +msgstr "local variable referenced before assignment" + +#: py/objint.c +msgid "long int not supported in this build" +msgstr "long int not supported in this build" + +#: ports/esp32s2/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" +msgstr "loopback + silent mode not supported by peripheral" + +#: py/parse.c +msgid "malformed f-string" +msgstr "malformed f-string" + +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" +msgstr "map buffer too small" + +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" +msgstr "math domain error" + +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" +msgstr "matrix is not positive definite" + +#: ports/nrf/common-hal/_bleio/Characteristic.c +#: ports/nrf/common-hal/_bleio/Descriptor.c +#, c-format +msgid "max_length must be 0-%d when fixed_length is %s" +msgstr "max_length must be 0-%d when fixed_length is %s" + +#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c +msgid "max_length must be >= 0" +msgstr "max_length must be >= 0" + +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is 4" +msgstr "maximum number of dimensions is 4" + +#: py/runtime.c +msgid "maximum recursion depth exceeded" +msgstr "maximum recursion depth exceeded" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" +msgstr "maxiter must be > 0" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" +msgstr "maxiter should be > 0" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "median argument must be an ndarray" +msgstr "median argument must be an ndarray" + +#: py/runtime.c +#, c-format +msgid "memory allocation failed, allocating %u bytes" +msgstr "memory allocation failed, allocating %u bytes" + +#: py/runtime.c +msgid "memory allocation failed, heap is locked" +msgstr "memory allocation failed, heap is locked" + +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "memoryview: length is not a multiple of itemsize" + +#: py/builtinimport.c +msgid "module not found" +msgstr "module not found" + +#: extmod/ulab/code/numpy/poly/poly.c +msgid "more degrees of freedom than data points" +msgstr "more degrees of freedom than data points" + +#: py/compile.c +msgid "multiple *x in assignment" +msgstr "multiple *x in assignment" + +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" +msgstr "multiple bases have instance lay-out conflict" + +#: py/objtype.c +msgid "multiple inheritance not supported" +msgstr "multiple inheritance not supported" + +#: py/emitnative.c +msgid "must raise an object" +msgstr "must raise an object" + +#: py/modbuiltins.c +msgid "must use keyword argument for key function" +msgstr "must use keyword argument for key function" + +#: py/runtime.c +msgid "name '%q' is not defined" +msgstr "name '%q' is not defined" + +#: py/runtime.c +msgid "name not defined" +msgstr "name not defined" + +#: py/compile.c +msgid "name reused for argument" +msgstr "name reused for argument" + +#: py/emitnative.c +msgid "native yield" +msgstr "native yield" + +#: py/runtime.c +#, c-format +msgid "need more than %d values to unpack" +msgstr "need more than %d values to unpack" + +#: py/modmath.c +msgid "negative factorial" +msgstr "" + +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" +msgstr "negative power with no float support" + +#: py/objint_mpz.c py/runtime.c +msgid "negative shift count" +msgstr "negative shift count" + +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" +msgstr "no SD card" + +#: py/vm.c +msgid "no active exception to reraise" +msgstr "no active exception to reraise" + +#: shared-bindings/socket/__init__.c shared-module/network/__init__.c +msgid "no available NIC" +msgstr "no available NIC" + +#: py/compile.c +msgid "no binding for nonlocal found" +msgstr "no binding for nonlocal found" + +#: shared-module/msgpack/__init__.c +msgid "no default packer" +msgstr "no default packer" + +#: py/builtinimport.c +msgid "no module named '%q'" +msgstr "no module named '%q'" + +#: shared-bindings/displayio/FourWire.c shared-bindings/displayio/I2CDisplay.c +#: shared-bindings/displayio/ParallelBus.c +msgid "no reset pin available" +msgstr "no reset pin available" + +#: shared-module/sdcardio/SDCard.c +msgid "no response from SD card" +msgstr "no response from SD card" + +#: py/runtime.c +msgid "no such attribute" +msgstr "no such attribute" + +#: ports/nrf/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" +msgstr "non-UUID found in service_uuids_whitelist" + +#: py/compile.c +msgid "non-default argument follows default argument" +msgstr "non-default argument follows default argument" + +#: extmod/modubinascii.c +msgid "non-hex digit found" +msgstr "non-hex digit found" + +#: py/compile.c +msgid "non-keyword arg after */**" +msgstr "non-keyword arg after */**" + +#: py/compile.c +msgid "non-keyword arg after keyword arg" +msgstr "non-keyword arg after keyword arg" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" +msgstr "non-zero timeout must be > 0.01" + +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" +msgstr "non-zero timeout must be >= interval" + +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" +msgstr "not a 128-bit UUID" + +#: py/objstr.c +msgid "not all arguments converted during string formatting" +msgstr "not all arguments converted during string formatting" + +#: py/objstr.c +msgid "not enough arguments for format string" +msgstr "not enough arguments for format string" + +#: extmod/ulab/code/ulab_create.c +msgid "number of points must be at least 2" +msgstr "number of points must be at least 2" + +#: py/builtinhelp.c +msgid "object " +msgstr "object " + +#: py/obj.c +msgid "object '%q' is not a tuple or list" +msgstr "object '%q' is not a tuple or list" + +#: py/obj.c +msgid "object does not support item assignment" +msgstr "object does not support item assignment" + +#: py/obj.c +msgid "object does not support item deletion" +msgstr "object does not support item deletion" + +#: py/obj.c +msgid "object has no len" +msgstr "object has no len" + +#: py/obj.c +msgid "object is not subscriptable" +msgstr "object is not subscriptable" + +#: py/runtime.c +msgid "object not an iterator" +msgstr "object not an iterator" + +#: py/objtype.c py/runtime.c +msgid "object not callable" +msgstr "object not callable" + +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" +msgstr "object not in sequence" + +#: py/runtime.c +msgid "object not iterable" +msgstr "object not iterable" + +#: py/obj.c +msgid "object of type '%q' has no len()" +msgstr "object of type '%q' has no len()" + +#: py/obj.c +msgid "object with buffer protocol required" +msgstr "object with buffer protocol required" + +#: extmod/modubinascii.c +msgid "odd-length string" +msgstr "odd-length string" + +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c +msgid "offset is too large" +msgstr "offset is too large" + +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" +msgstr "offset must be >= 0" + +#: extmod/ulab/code/ulab_create.c +msgid "offset must be non-negative and no greater than buffer length" +msgstr "offset must be non-negative and not greater than buffer length" + +#: py/objstr.c py/objstrunicode.c +msgid "offset out of bounds" +msgstr "offset out of bounds" + +#: ports/nrf/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" +msgstr "only bit_depth=16 is supported" + +#: ports/nrf/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" +msgstr "only sample_rate=16000 is supported" + +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" +msgstr "only slices with step=1 (aka None) are supported" + +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c +msgid "operands could not be broadcast together" +msgstr "operands could not be broadcast together" + +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" +msgstr "operation is implemented for 1D Boolean arrays only" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "operation is not implemented on ndarrays" +msgstr "operation is not implemented on ndarrays" + +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" +msgstr "operation is not supported for given type" + +#: py/modbuiltins.c +msgid "ord expects a character" +msgstr "ord expects a character" + +#: py/modbuiltins.c +#, c-format +msgid "ord() expected a character, but string of length %d found" +msgstr "ord() expected a character, but string of length %d found" + +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + +#: shared-bindings/displayio/Bitmap.c +msgid "out of range of source" +msgstr "out of range of source" + +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c +msgid "out of range of target" +msgstr "out of range of target" + +#: py/objint_mpz.c +msgid "overflow converting long int to machine word" +msgstr "overflow converting long int to machine word" + +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" +msgstr "pack expected %d items for packing (got %d)" + +#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c +msgid "palette must be 32 bytes long" +msgstr "palette must be 32 bytes long" + +#: shared-bindings/displayio/Palette.c +msgid "palette_index should be an int" +msgstr "palette_index should be an int" + +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" +msgstr "parameters must be registers in sequence a2 to a5" + +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" +msgstr "parameters must be registers in sequence r0 to r3" + +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c +msgid "pixel coordinates out of bounds" +msgstr "pixel coordinates out of bounds" + +#: shared-bindings/displayio/Bitmap.c +msgid "pixel value requires too many bits" +msgstr "pixel value requires too many bits" + +#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +msgid "pixel_shader must be displayio.Palette or displayio.ColorConverter" +msgstr "pixel_shader must be displayio.Palette or displayio.ColorConverter" + +#: shared-module/vectorio/Polygon.c +msgid "polygon can only be registered in one parent" +msgstr "polygon can only be registered in one parent" + +#: ports/esp32s2/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" +msgstr "pop from an empty PulseIn" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c +#: shared-bindings/ps2io/Ps2.c +msgid "pop from empty %q" +msgstr "pop from empty %q" + +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "port must be >= 0" + +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" +msgstr "pow() 3rd argument cannot be 0" + +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" +msgstr "pow() with 3 arguments requires integers" + +#: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h +#: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h +#: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h +#: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h +#: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h +#: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h +#: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h +#: ports/esp32s2/boards/targett_module_clip_wroom/mpconfigboard.h +#: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h +msgid "pressing boot button at start up.\n" +msgstr "pressing boot button at start up.\n" + +#: ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.h +#: ports/atmel-samd/boards/circuitplayground_express_crickit/mpconfigboard.h +#: ports/atmel-samd/boards/circuitplayground_express_displayio/mpconfigboard.h +#: ports/atmel-samd/boards/escornabot_makech/mpconfigboard.h +#: ports/atmel-samd/boards/meowmeow/mpconfigboard.h +msgid "pressing both buttons at start up.\n" +msgstr "pressing both buttons at start up.\n" + +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "pull masks conflict with direction masks" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "pull_threshold must be between 1 and 32" +msgstr "pull_threshold must be between 1 and 32" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "push_threshold must be between 1 and 32" +msgstr "push_threshold must be between 1 and 32" + +#: extmod/modutimeq.c +msgid "queue overflow" +msgstr "queue overflow" + +#: py/parse.c +msgid "raw f-strings are not implemented" +msgstr "raw f-strings are not implemented" + +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" +msgstr "real and imaginary parts must be of equal length" + +#: py/builtinimport.c +msgid "relative import" +msgstr "relative import" + +#: py/obj.c +#, c-format +msgid "requested length %d but object has length %d" +msgstr "requested length %d but object has length %d" + +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" +msgstr "results cannot be cast to specified type" + +#: py/compile.c +msgid "return annotation must be an identifier" +msgstr "return annotation must be an identifier" + +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" +msgstr "return expected '%q' but got '%q'" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] duplicates another pin assignment" +msgstr "rgb_pins[%d] duplicates another pin assignment" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] is not on the same port as clock" +msgstr "rgb_pins[%d] is not on the same port as clock" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "roll argument must be an ndarray" +msgstr "roll argument must be an ndarray" + +#: py/objstr.c +msgid "rsplit(None,n)" +msgstr "rsplit(None,n)" + +#: shared-bindings/audiocore/RawSample.c +msgid "" +"sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or " +"'B'" +msgstr "" +"sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or " +"'B'" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" +msgstr "sampling rate out of range" + +#: py/modmicropython.c +msgid "schedule stack full" +msgstr "schedule stack full" + +#: lib/utils/pyexec.c py/builtinimport.c +msgid "script compilation not supported" +msgstr "script compilation not supported" + +#: extmod/ulab/code/ndarray.c +msgid "shape must be a tuple" +msgstr "shape must be a tuple" + +#: shared-module/msgpack/__init__.c +msgid "short read" +msgstr "short read" + +#: py/objstr.c +msgid "sign not allowed in string format specifier" +msgstr "sign not allowed in string format specifier" + +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" +msgstr "sign not allowed with integer format specifier 'c'" + +#: py/objstr.c +msgid "single '}' encountered in format string" +msgstr "single '}' encountered in format string" + +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" +msgstr "size is defined for ndarrays only" + +#: shared-bindings/time/__init__.c +msgid "sleep length must be non-negative" +msgstr "sleep length must be non-negative" + +#: extmod/ulab/code/ndarray.c +msgid "slice step can't be zero" +msgstr "slice step can't be zero" + +#: py/objslice.c py/sequence.c +msgid "slice step cannot be zero" +msgstr "slice step cannot be zero" + +#: py/objint.c py/sequence.c +msgid "small int overflow" +msgstr "small int overflow" + +#: main.c +msgid "soft reboot\n" +msgstr "soft reboot\n" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "sort argument must be an ndarray" +msgstr "sort argument must be an ndarray" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" +msgstr "sos array must be of shape (n_section, 6)" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" +msgstr "sos[:, 3] should be all ones" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" +msgstr "sosfilt requires iterable arguments" + +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c +msgid "source palette too large" +msgstr "source palette too large" + +#: py/objstr.c +msgid "start/end indices" +msgstr "start/end indices" + +#: shared-bindings/displayio/Shape.c +msgid "start_x should be an int" +msgstr "start_x should be an int" + +#: shared-bindings/random/__init__.c +msgid "step must be non-zero" +msgstr "step must be non-zero" + +#: shared-bindings/busio/UART.c +msgid "stop must be 1 or 2" +msgstr "stop must be 1 or 2" + +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" +msgstr "stop not reachable from start" + +#: py/stream.c +msgid "stream operation not supported" +msgstr "stream operation not supported" + +#: py/objstrunicode.c +msgid "string indices must be integers, not %q" +msgstr "string indices must be integers, not %q" + +#: py/stream.c +msgid "string not supported; use bytes or bytearray" +msgstr "string not supported; use bytes or bytearray" + +#: extmod/moductypes.c +msgid "struct: cannot index" +msgstr "struct: cannot index" + +#: extmod/moductypes.c +msgid "struct: no fields" +msgstr "struct: no fields" + +#: py/objarray.c py/objstr.c +msgid "substring not found" +msgstr "substring not found" + +#: py/compile.c +msgid "super() can't find self" +msgstr "super() can't find self" + +#: extmod/modujson.c +msgid "syntax error in JSON" +msgstr "syntax error in JSON" + +#: extmod/moductypes.c +msgid "syntax error in uctypes descriptor" +msgstr "syntax error in uctypes descriptor" + +#: shared-bindings/touchio/TouchIn.c +msgid "threshold must be in the range 0-65536" +msgstr "threshold must be in the range 0-65536" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "tile must be greater than zero" +msgstr "tile must be greater than zero" + +#: shared-bindings/time/__init__.c +msgid "time.struct_time() takes a 9-sequence" +msgstr "time.struct_time() takes a 9-sequence" + +#: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c +#: ports/nrf/common-hal/watchdog/WatchDogTimer.c +#: ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" +msgstr "timeout duration exceeded the maximum supported value" + +#: shared-bindings/busio/UART.c +msgid "timeout must be 0.0-100.0 seconds" +msgstr "timeout must be 0.0-100.0 seconds" + +#: ports/nrf/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" +msgstr "timeout must be < 655.35 secs" + +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "timeout must be >= 0.0" +msgstr "timeout must be >= 0.0" + +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v1 card" +msgstr "timeout waiting for v1 card" + +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v2 card" +msgstr "timeout waiting for v2 card" + +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" +msgstr "timestamp out of range for platform time_t" + +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" +msgstr "tobytes can be invoked for dense arrays only" + +#: shared-module/struct/__init__.c +msgid "too many arguments provided with the given format" +msgstr "too many arguments provided with the given format" + +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c +msgid "too many dimensions" +msgstr "too many dimensions" + +#: extmod/ulab/code/ndarray.c +msgid "too many indices" +msgstr "too many indices" + +#: py/runtime.c +#, c-format +msgid "too many values to unpack (expected %d)" +msgstr "too many values to unpack (expected %d)" + +#: extmod/ulab/code/numpy/approx/approx.c +msgid "trapz is defined for 1D arrays" +msgstr "trapz is defined for 1D arrays" + +#: extmod/ulab/code/numpy/approx/approx.c +msgid "trapz is defined for 1D arrays of equal length" +msgstr "trapz is defined for 1D arrays of equal length" + +#: py/obj.c +msgid "tuple/list has wrong length" +msgstr "tuple/list has wrong length" + +#: ports/esp32s2/common-hal/canio/CAN.c +#, c-format +msgid "twai_driver_install returned esp-idf error #%d" +msgstr "twai_driver_install returned esp-idf error #%d" + +#: ports/esp32s2/common-hal/canio/CAN.c +#, c-format +msgid "twai_start returned esp-idf error #%d" +msgstr "twai_start returned esp-idf error #%d" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" +msgstr "tx and rx cannot both be None" + +#: py/objtype.c +msgid "type '%q' is not an acceptable base type" +msgstr "type '%q' is not an acceptable base type" + +#: py/objtype.c +msgid "type is not an acceptable base type" +msgstr "type is not an acceptable base type" + +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" +msgstr "type object '%q' has no attribute '%q'" + +#: py/objgenerator.c +msgid "type object 'generator' has no attribute '__await__'" +msgstr "type object 'generator' has no attribute '__await__'" + +#: py/objtype.c +msgid "type takes 1 or 3 arguments" +msgstr "type takes 1 or 3 arguments" + +#: py/objint_longlong.c +msgid "ulonglong too large" +msgstr "ulonglong too large" + +#: py/emitnative.c +msgid "unary op %q not implemented" +msgstr "unary op %q not implemented" + +#: py/parse.c +msgid "unexpected indent" +msgstr "unexpected indent" + +#: py/bc.c +msgid "unexpected keyword argument" +msgstr "unexpected keyword argument" + +#: py/bc.c py/objnamedtuple.c +msgid "unexpected keyword argument '%q'" +msgstr "unexpected keyword argument '%q'" + +#: py/lexer.c +msgid "unicode name escapes" +msgstr "unicode name escapes" + +#: py/parse.c +msgid "unindent does not match any outer indentation level" +msgstr "unindent does not match any outer indentation level" + +#: py/objstr.c +#, c-format +msgid "unknown conversion specifier %c" +msgstr "unknown conversion specifier %c" + +#: py/objstr.c +msgid "unknown format code '%c' for object of type '%q'" +msgstr "unknown format code '%c' for object of type '%q'" + +#: py/compile.c +msgid "unknown type" +msgstr "unknown type" + +#: py/compile.c +msgid "unknown type '%q'" +msgstr "unknown type '%q'" + +#: py/objstr.c +msgid "unmatched '{' in format" +msgstr "unmatched '{' in format" + +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" +msgstr "unreadable attribute" + +#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-module/vectorio/Polygon.c +msgid "unsupported %q type" +msgstr "unsupported %q type" + +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" +msgstr "unsupported Thumb instruction '%s' with %d arguments" + +#: py/emitinlinextensa.c +#, c-format +msgid "unsupported Xtensa instruction '%s' with %d arguments" +msgstr "unsupported Xtensa instruction '%s' with %d arguments" + +#: py/objstr.c +#, c-format +msgid "unsupported format character '%c' (0x%x) at index %d" +msgstr "unsupported format character '%c' (0x%x) at index %d" + +#: py/runtime.c +msgid "unsupported type for %q: '%q'" +msgstr "unsupported type for %q: '%q'" + +#: py/runtime.c +msgid "unsupported type for operator" +msgstr "unsupported type for operator" + +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" +msgstr "unsupported types for %q: '%q', '%q'" + +#: py/objint.c +#, c-format +msgid "value must fit in %d byte(s)" +msgstr "value must fit in %d byte(s)" + +#: shared-bindings/displayio/Bitmap.c +msgid "value_count must be > 0" +msgstr "value_count must be > 0" + +#: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c +msgid "watchdog not initialized" +msgstr "WatchDog not initialised" + +#: shared-bindings/watchdog/WatchDogTimer.c +msgid "watchdog timeout must be greater than 0" +msgstr "WatchDog timeout must be greater than 0" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "width must be from 2 to 8 (inclusive), not %d" + +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "width must be greater than zero" +msgstr "width must be greater than zero" + +#: ports/esp32s2/common-hal/wifi/Radio.c +msgid "wifi is not enabled" +msgstr "WiFi is not enabled" + +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" +msgstr "window must be <= interval" + +#: extmod/ulab/code/numpy/numerical/numerical.c +msgid "wrong axis index" +msgstr "wrong axis index" + +#: extmod/ulab/code/ulab_create.c +msgid "wrong axis specified" +msgstr "wrong axis specified" + +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c +msgid "wrong input type" +msgstr "wrong input type" + +#: extmod/ulab/code/ulab_create.c py/objstr.c +msgid "wrong number of arguments" +msgstr "wrong number of arguments" + +#: py/runtime.c +msgid "wrong number of values to unpack" +msgstr "wrong number of values to unpack" + +#: extmod/ulab/code/ndarray.c +msgid "wrong operand type" +msgstr "wrong operand type" + +#: extmod/ulab/code/numpy/vector/vector.c +msgid "wrong output type" +msgstr "wrong output type" + +#: shared-module/displayio/Shape.c +msgid "x value out of bounds" +msgstr "x value out of bounds" + +#: ports/esp32s2/common-hal/audiobusio/__init__.c +msgid "xTaskCreate failed" +msgstr "xTaskCreate failed" + +#: shared-bindings/displayio/Shape.c +msgid "y should be an int" +msgstr "y should be an int" + +#: shared-module/displayio/Shape.c +msgid "y value out of bounds" +msgstr "y value out of bounds" + +#: py/objrange.c +msgid "zero step" +msgstr "zero step" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" +msgstr "zi must be an ndarray" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" +msgstr "zi must be of float type" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" +msgstr "zi must be of shape (n_section, 2)" + +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper functions don't currently support more than 4 arguments" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "address %08x is not aligned to %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "function does not take keyword arguments" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotation must be an identifier" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Total data to write is larger than outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 & 4 do not support internal pullup in sleep" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "Buffer must be a bytes-like object" + +#~ msgid "io must be rtc io" +#~ msgstr "io must be rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "trigger level must be 0 or 1" + +#~ msgid "wakeup conflict" +#~ msgstr "wakeup conflict" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Attempted heap allocation when MicroPython VM not running." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR jump failed. Likely memory corruption." + +#, fuzzy +#~ msgid "MicroPython fatal error." +#~ msgstr "CircuitPython fatal error." + +#~ msgid "argument must be ndarray" +#~ msgstr "argument must be ndarray" + +#~ msgid "norm is defined for 1D and 2D arrays" +#~ msgstr "norm is defined for 1D and 2D arrays" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Nordic Soft Device failure assertion." + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Unknown soft device error: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "first argument must be an iterable" + +#~ msgid "iterables are not of the same length" +#~ msgstr "iterables are not of the same length" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Selected CTS pin not valid" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Selected RTS pin not valid" diff --git a/locale/es.po b/locale/es.po index b446ceb4847ba..2b0538e8b3ae0 100644 --- a/locale/es.po +++ b/locale/es.po @@ -8,27 +8,31 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2020-12-30 22:25+0000\n" -"Last-Translator: Hugo Dahl \n" +"PO-Revision-Date: 2021-04-22 17:16+0000\n" +"Last-Translator: Jose David M \n" "Language-Team: \n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" -"X-Generator: Weblate 4.4.1-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" "\n" "Code done running.\n" msgstr "" +"\n" +"El código terminó de ejecutar.\n" #: main.c msgid "" "\n" "Code stopped by auto-reload.\n" msgstr "" +"\n" +"El código fue detenido por el auto-reiniciado.\n" #: supervisor/shared/safe_mode.c msgid "" @@ -50,7 +54,7 @@ msgstr " Archivo \"%q\", línea %d" #: py/builtinhelp.c msgid " is of type %q\n" -msgstr "" +msgstr " es de tipo %q\n" #: main.c msgid " output:\n" @@ -66,6 +70,8 @@ msgstr "%%c requiere int o char" msgid "" "%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" msgstr "" +"%d pines de dirección, %d pines rgb y %d tiles indican una altura de %d, y " +"no de %d" #: ports/atmel-samd/common-hal/sdioio/SDCard.c msgid "%q failure: %d" @@ -78,6 +84,7 @@ msgstr "%q está siendo utilizado" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -107,6 +114,7 @@ msgstr "%q debe ser >= 1" msgid "%q must be a tuple of length 2" msgstr "%q debe ser una tupla de longitud 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q fuera de rango" @@ -126,7 +134,7 @@ msgstr "%q() toma %d argumentos posicionales pero %d fueron dados" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c #, c-format msgid "%s error 0x%x" -msgstr "" +msgstr "%s error 0x%x" #: py/argcheck.c msgid "'%q' argument required" @@ -292,7 +300,7 @@ msgstr "pow() con 3 argumentos no soportado" #: shared-module/msgpack/__init__.c msgid "64 bit types" -msgstr "" +msgstr "tipos de 64 bit" #: ports/atmel-samd/common-hal/countio/Counter.c #: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c @@ -337,16 +345,21 @@ msgid "All SPI peripherals are in use" msgstr "Todos los periféricos SPI están siendo usados" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Todos los periféricos UART están siendo usados" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "Todos los canales esta en uso" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Todos los canales de eventos estan siendo usados" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "All state machines in use" -msgstr "" +msgstr "Todas las máquinas de estado en uso" #: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "All sync event channels in use" @@ -370,6 +383,7 @@ msgstr "Todos los timers para este pin están siendo utilizados" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Todos los timers en uso" @@ -410,6 +424,10 @@ msgstr "AnalogOut es solo de 16 bits. El valor debe ser menor que 65536." msgid "AnalogOut not supported on given pin" msgstr "El pin proporcionado no soporta AnalogOut" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "Otra salida PWMAudioOut esta ya activada" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -433,10 +451,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Tratando de localizar %d bloques" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "" -"Se intentó asignación del montículo, sin que la VM de MicroPython esté " -"ejecutando." +msgid "Attempted heap allocation when VM not running." +msgstr "Asignación del montículo mientras la VM no esta ejecutándose." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -463,6 +479,10 @@ msgstr "El periférico no maneja el Baudrate" msgid "Below minimum frame rate" msgstr "Por debajo de la tasa mínima de refrescamiento" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "Le reloj de bit y de selector de palabra deben ser pines secuenciales" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Bit clock y word select deben compartir una unidad de reloj" @@ -504,6 +524,11 @@ msgstr "El brillo no se puede ajustar" msgid "Buffer + offset too small %d %d %d" msgstr "Búfer + compensado muy pequeños %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" +"Los elementos del búfer deben de ser de una longitud de 4 bytes o menos" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -520,6 +545,7 @@ msgid "Buffer is too small" msgstr "El buffer es muy pequeño" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "Longitud del buffer %d es demasiado grande. Tiene que ser menor a %d" @@ -549,6 +575,7 @@ msgstr "Búffer muy corto por %d bytes" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Bus pin %d ya está siendo utilizado" @@ -567,7 +594,7 @@ msgstr "Los bloques CBC deben ser múltiplos de 16 bytes" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "CRC or checksum was invalid" -msgstr "" +msgstr "CRC o suma de comprobación inválida" #: py/objtype.c msgid "Call super().__init__() before accessing native object." @@ -575,15 +602,17 @@ msgstr "Llame a super().__ init __() antes de acceder al objeto nativo." #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Can only alarm on RTC IO from deep sleep." -msgstr "" +msgstr "Solo puede alertar en RTC IO de deep sleep." #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Can only alarm on one low pin while others alarm high from deep sleep." msgstr "" +"Solo puede alertar en un pin low mientras los otros alertan en high viniendo " +"de deep sleep." #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Can only alarm on two low pins from deep sleep." -msgstr "" +msgstr "Solo puede alerta en dos low pines viniendo de deep sleep." #: ports/nrf/common-hal/_bleio/Characteristic.c msgid "Can't set CCCD on local Characteristic" @@ -622,7 +651,7 @@ msgstr "No se puede tener ambos canales en el mismo pin" #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Cannot pull on input-only pin." -msgstr "" +msgstr "No puede hacer pull en un pin de entrada sola." #: shared-module/bitbangio/SPI.c msgid "Cannot read without MISO pin." @@ -642,6 +671,10 @@ msgstr "No se puede volver a montar '/' cuando el USB esta activo." msgid "Cannot reset into bootloader because no bootloader is present." msgstr "No se puede reiniciar a bootloader porque no hay bootloader presente." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "No se pueden definir opciones para enchufe" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "No se puede asignar un valor cuando la dirección es input." @@ -663,13 +696,13 @@ msgstr "No se puede transmitir sin pines MOSI y MISO." msgid "Cannot unambiguously get sizeof scalar" msgstr "No se puede obtener inequívocamente sizeof escalar" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "No puede variar la frecuencia en un temporizador que ya está en uso" #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Cannot wake on pin edge. Only level." -msgstr "" +msgstr "No puede despertar en pin edge, solo en nivel." #: shared-module/bitbangio/SPI.c msgid "Cannot write without MOSI pin." @@ -749,14 +782,6 @@ msgstr "No se pudo inicializar SDCard" msgid "Could not initialize UART" msgstr "No se puede inicializar la UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "No se pudo inicializar el canal" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "No se pudo inicializar el temporizador" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "No se pudo reiniciar el canal" @@ -777,7 +802,7 @@ msgstr "No puedo traer el reloj" msgid "Could not set address" msgstr "No se puede definir la dirección" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "No se pudo iniciar PWM" @@ -826,7 +851,7 @@ msgstr "El pin Data 0 debe estar alineado a bytes" #: ports/esp32s2/common-hal/displayio/ParallelBus.c msgid "Data 0 pin must be byte aligned." -msgstr "" +msgstr "El pin de datos 0 debe ser alineado a byte." #: shared-module/audiocore/WaveFile.c msgid "Data chunk must follow fmt chunk" @@ -878,13 +903,18 @@ msgstr "Fallo ESP-IDF al tomar la memoria" msgid "EXTINT channel already in use" msgstr "El canal EXTINT ya está siendo utilizado" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Error en el flujo MIDI en la posición %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Error en regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" -msgstr "" +msgstr "Error: fallo al vincular" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c py/enum.c #: shared-bindings/_bleio/__init__.c shared-bindings/aesio/aes.c @@ -922,7 +952,7 @@ msgstr "Se esperaba una dirección" #: shared-bindings/alarm/__init__.c msgid "Expected an alarm" -msgstr "" +msgstr "Un objecto alarm era esperado" #: shared-module/_pixelbuf/PixelBuf.c #, c-format @@ -933,15 +963,15 @@ msgstr "Se esperaba un tuple de %d, se obtuvo %d" msgid "Extended advertisements with scan response not supported." msgstr "No se admiten anuncios extendidos con respuesta de escaneo." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "FFT se define solo para ndarrays" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "FFT solo esta implementado para arrays lineales" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "Fallo en saludo SSL" @@ -955,6 +985,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "No se puede adquirir el mutex, error 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Ha fallado la asignación del buffer RX" @@ -963,6 +994,7 @@ msgstr "Ha fallado la asignación del buffer RX" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -976,6 +1008,10 @@ msgstr "Fallo al tomar memoria Wifi" msgid "Failed to allocate wifi scan memory" msgstr "Fallo al tomar memoria para búsqueda wifi" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "Fallo al hacer el búfer de la muestra" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Error al conectar: error interno" @@ -1001,6 +1037,10 @@ msgstr "No se puede liberar el mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Error al escribir el flash interno." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Error grave." + #: py/moduerrno.c msgid "File exists" msgstr "El archivo ya existe" @@ -1013,7 +1053,7 @@ msgstr "Filtros muy complejos" #: ports/esp32s2/common-hal/dualbank/__init__.c msgid "Firmware image is invalid" -msgstr "" +msgstr "La imagen de firmware es inválida" #: ports/cxd56/common-hal/camera/Camera.c msgid "Format not supported" @@ -1024,7 +1064,7 @@ msgstr "Sin capacidades para el formato" msgid "Framebuffer requires %d bytes" msgstr "Framebuffer requiere %d bytes" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" "La frecuencia debe coincidir con PWMOut existente usando este temporizador" @@ -1036,7 +1076,7 @@ msgstr "La función requiere lock" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Generic Failure" -msgstr "" +msgstr "Fallo Genérico" #: shared-bindings/displayio/Display.c #: shared-bindings/displayio/EPaperDisplay.c @@ -1044,10 +1084,6 @@ msgstr "" msgid "Group already used" msgstr "Grupo ya está siendo utilizado" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Group lleno" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1072,21 +1108,22 @@ msgstr "I2C Error de inicio" #: ports/raspberrypi/common-hal/busio/I2C.c msgid "I2C peripheral in use" -msgstr "" +msgstr "Dispositivo I2C en uso" #: shared-bindings/audiobusio/I2SOut.c msgid "I2SOut not available" msgstr "I2SOut no disponible" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IV debe tener %d bytes de longitud" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" +"Los elementos del búfer de entrada deben ser de una longitud <= 4 bytes" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1101,12 +1138,31 @@ msgstr "Tamaño incorrecto del buffer" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Init program size invalid" +msgstr "Tamaño del programa Init invalido" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" +"La dirección configurada inicial del pin esta en conflicto con la dirección " +"de salida inicial del pin" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" msgstr "" +"El estado inicial del pin de configuración esta en conflicto con el estado " +"inicial de salida del pin" #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "Inicializacion fallida por falta de memoria" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" +"La longitud del buffer de entrada(%d) debe ser un múltiplo del conteo de la " +"tira (%d)" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "La entrada está durando mucho tiempo" @@ -1118,27 +1174,27 @@ msgstr "error Input/output" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d jumps on pin" -msgstr "" +msgstr "La instruction %d salta en pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts in more bits than pin count" -msgstr "" +msgstr "La instruccion %d mueve mas bits que la cuenta del pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts out more bits than pin count" -msgstr "" +msgstr "La instruccion %d mueve mas bits que la cuenta del pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d uses extra pin" -msgstr "" +msgstr "La instrucción %d usa un pin extra" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d waits on input outside of count" -msgstr "" +msgstr "La instrucción %d espera una entrada fuera del conteo" #: ports/nrf/common-hal/_bleio/__init__.c msgid "Insufficient authentication" @@ -1163,6 +1219,7 @@ msgstr "%q inválido" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Pin %q inválido" @@ -1189,15 +1246,21 @@ msgstr "BSSID inválido" msgid "Invalid DAC pin supplied" msgstr "Pin suministrado inválido para DAC" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "Archivo MIDI inválido" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Frecuencia PWM inválida" #: ports/esp32s2/common-hal/analogio/AnalogIn.c msgid "Invalid Pin" -msgstr "" +msgstr "Pin inválido" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c #: py/moduerrno.c shared-module/rgbmatrix/RGBMatrix.c @@ -1208,7 +1271,8 @@ msgstr "Argumento inválido" msgid "Invalid bits per value" msgstr "Inválido bits por valor" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Tamaño de buffer inválido" @@ -1237,14 +1301,10 @@ msgstr "Archivo inválido" msgid "Invalid format chunk size" msgstr "Formato de fragmento de formato no válido" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Frecuencia inválida" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Frecuencia suministrada no válida" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Acceso a memoria no válido." @@ -1283,17 +1343,13 @@ msgstr "Pin inválido para canal derecho" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "pines inválidos" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Pines inválidos para PWMOut" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1313,19 +1369,15 @@ msgstr "'security_mode' no válido" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Invalid size" -msgstr "" +msgstr "Tamaño incorrecto" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" -msgstr "" +msgstr "socket invalido para TLS" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Invalid state" -msgstr "" - -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" +msgstr "Estado invalido" #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" @@ -1339,14 +1391,11 @@ msgstr "Cuenta de voces inválida" msgid "Invalid wave file" msgstr "Archivo wave inválido" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Tamaño no válido de palabra/bit" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "La llave debe tener 16, 24 o 32 bytes de longitud" @@ -1373,7 +1422,7 @@ msgstr "Length no deberia ser negativa" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "MAC address was invalid" -msgstr "" +msgstr "La dirección MAC es incorrecta" #: shared-module/bitbangio/SPI.c msgid "MISO pin init failed." @@ -1392,14 +1441,6 @@ msgstr "Valor máximo de x cuando se refleja es %d" msgid "Messages limited to 8 bytes" msgstr "Mensajes limitados a 8 bytes" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR jump falló. Probable corrupción de la memoria." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Error fatal de MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Micrófono demora de inicio debe estar en el rango 0.0 a 1.0" @@ -1411,32 +1452,36 @@ msgstr "Falta el pin MISO o MOSI" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d reads pin(s)" -msgstr "" +msgstr "first-in-pin no encontrado. La instrucción %d lee el/los pin(es)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d shifts in from pin(s)" -msgstr "" +msgstr "first_in_pin no encontrado. La instrucción %d desplaza de los pin(es)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d waits based on pin" msgstr "" +"first_in_pin no encontrado. La instrucción %d espera basada en este pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d shifts out to pin(s)" msgstr "" +"first_in_pin no encontrado. La instrucción %d mueve hacia afuera hacia el/" +"los pin(es)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d writes pin(s)" -msgstr "" +msgstr "first_in_pin no encontrado. La instrucción %d escribe pin(es)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_set_pin. Instruction %d sets pin(s)" msgstr "" +"first_set_pin no encontrado. La instrucción %d configura el/los pin(es)" #: shared-bindings/displayio/Group.c msgid "Must be a %q subclass." @@ -1451,6 +1496,10 @@ msgstr "Debe proporcionar un pin MISO o MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Debe usar un múltiplo de 6 pines rgb, no %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "Salto NLR falló. Probablemente corrupción de memoria." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "Error NVS" @@ -1470,13 +1519,19 @@ msgstr "El chip no tiene DAC" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "No se encontró el canal DMA" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "timer por establecedor de paso DMA no encontrado" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" -msgstr "" +msgstr "No hay dispositivo I2C en la dirección: %x" #: ports/esp32s2/common-hal/busio/SPI.c ports/mimxrt10xx/common-hal/busio/SPI.c #: ports/stm/common-hal/busio/SPI.c @@ -1531,6 +1586,14 @@ msgstr "Sin soporte de hardware en el pin clk" msgid "No hardware support on pin" msgstr "Sin soporte de hardware en pin" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "No hay \"in\" en el programa" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "No hay \"in\" o \"out\" en el programa" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "No se especificó ninguna llave" @@ -1539,25 +1602,19 @@ msgstr "No se especificó ninguna llave" msgid "No long integer support" msgstr "No hay soporte de entero largo" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "No hay más canales disponibles" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "No hay más temporizadores disponibles" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "No hay más temporizadores disponibles en este pin." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "No hay una red con ese ssid" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No out in program" -msgstr "" +msgstr "No hay out en el programa" + +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "No se encontró pull up en SDA or SCL; verifique su cableado" #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" @@ -1576,13 +1633,18 @@ msgid "No timer available" msgstr "No hay temporizador disponible" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Fallo de aserción de dispositivo Nordic Soft." +msgid "Nordic system firmware failure assertion." +msgstr "Falla en la aserción del firmware del dispositivo Nordic." + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "El firmware del sistema Nordic no tiene memoria" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "No es una cadena de IP válida" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1613,13 +1675,10 @@ msgid "Odd parity is not supported" msgstr "Paridad impar no soportada" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Solo mono de 8 ó 16 bit con " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "Solo hay capacidad para direcciones IPv4" @@ -1647,11 +1706,11 @@ msgstr "" #: ports/esp32s2/common-hal/alarm/touch/TouchAlarm.c msgid "Only one TouchAlarm can be set in deep sleep." -msgstr "" +msgstr "Solamente una TouchAlarm puede ser configurada durante deep sleep." #: ports/esp32s2/common-hal/alarm/time/TimeAlarm.c msgid "Only one alarm.time alarm can be set." -msgstr "" +msgstr "Solamente una alarm.time puede ser configurada." #: shared-module/displayio/ColorConverter.c msgid "Only one color can be transparent at a time" @@ -1663,27 +1722,36 @@ msgstr "Solo se aceptan enteros crudos para ip" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Operation or feature not supported" -msgstr "" +msgstr "Operación no característica no soportada" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Operation timed out" -msgstr "" +msgstr "Tiempo de espera agotado" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Out of memory" -msgstr "" +msgstr "Memoria agotada" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "Se acabaron los enchufes" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "Los elementos del búfer de salida deben ser de una longitud <= 4 bytes" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "buffer de salida debe ser de por lo menos %d bytes" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "El sobremuestreo debe ser un múltiplo de 8." #: shared-bindings/audiobusio/PDMIn.c msgid "PDMIn not available" -msgstr "" +msgstr "PDMIn no esta disponible" #: shared-bindings/pwmio/PWMOut.c msgid "" @@ -1697,15 +1765,22 @@ msgstr "" "La frecuencia de PWM no se puede escribir variable_frequency es False en la " "construcción." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "Segmento PWM ya esta en uso" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "Segmento del PWM canal A ya esta en uso" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBus todavía no soportado" #: ports/esp32s2/common-hal/audiobusio/__init__.c msgid "Peripheral in use" -msgstr "" +msgstr "Periférico en uso" #: py/moduerrno.c msgid "Permission denied" @@ -1713,11 +1788,11 @@ msgstr "Permiso denegado" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Pin count must be at least 1" -msgstr "" +msgstr "El total de pines debe ser por lo menos 1" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Pin count too large" -msgstr "" +msgstr "Total de pines demasiado grande" #: ports/atmel-samd/common-hal/analogio/AnalogIn.c #: ports/cxd56/common-hal/analogio/AnalogIn.c @@ -1734,6 +1809,10 @@ msgstr "Pin no tiene capacidad ADC" msgid "Pin is input only" msgstr "El pin es solo de entrada" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "El pin debe estar en el PWM canal B" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "El pin debe admitir interrupciones de hardware" @@ -1753,6 +1832,14 @@ msgstr "" "ideales. Si esto no se puede evitar, pase allow_inefficient=True al " "constructor" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "Los pines deben estar en orden secuencial" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "Los pines deben compartir la división PWM" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Además de cualquier módulo en el sistema de archivos\n" @@ -1787,30 +1874,33 @@ msgstr "El prefijo del buffer debe estar en el heap" #: main.c msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" msgstr "" +"Presiona cualquier tecla para entrar al REPL. Usa CTRL-D para recargar.\n" #: main.c msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" msgstr "" +"Pretendiendo ir a deep sleep hasta la alarma, CTRL-C or una escritura de " +"archivo\n" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does IN without loading ISR" -msgstr "" +msgstr "El programa hace un IN sin cargar ISR" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does OUT without loading OSR" -msgstr "" +msgstr "El programa hace OUT sin cargar OSR" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program must contain at least one 16-bit instruction." -msgstr "" +msgstr "El programa debe contener por lo menos una instrucción de 16 bits." #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program size invalid" -msgstr "" +msgstr "El tamaño del programa no es correcto" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program too large" -msgstr "" +msgstr "Programa demasiado grande" #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." @@ -1818,7 +1908,7 @@ msgstr "Pull no se usa cuando la dirección es output." #: ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c msgid "RAISE mode is not implemented" -msgstr "" +msgstr "El modo RAISE no esta implementado" #: ports/stm/common-hal/os/__init__.c msgid "RNG DeInit Error" @@ -1828,6 +1918,10 @@ msgstr "Error de desinicialización de RNG" msgid "RNG Init Error" msgstr "Error de inicialización de RNG" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "RS485 no esta soportado todavía en este dispositivo" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1835,6 +1929,7 @@ msgstr "Se especifica inversión de RS485 si no está en modo RS485" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "Calibración de RTC no es soportada en esta placa" @@ -1843,7 +1938,7 @@ msgid "RTC is not supported on this board" msgstr "RTC no soportado en esta placa" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "Sin capacidad de RTS/CTS/RS485 para este dispositivo" @@ -1866,7 +1961,7 @@ msgstr "Objeto de solo-lectura" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Received response was invalid" -msgstr "" +msgstr "La respuesta recibida es invalida" #: shared-bindings/displayio/EPaperDisplay.c msgid "Refresh too soon" @@ -1882,7 +1977,7 @@ msgstr "El modo AES solicitado no es compatible" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Requested resource not found" -msgstr "" +msgstr "Recurso solicitado no encontrado" #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "Right channel unsupported" @@ -1900,12 +1995,6 @@ msgstr "¡Corriendo en modo seguro! " msgid "SD card CSD format not supported" msgstr "Sin capacidad para formato CSD para tarjeta SD" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA o SCL necesitan una pull up" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1926,7 +2015,7 @@ msgstr "Error de reinicialización de SPI" #: ports/raspberrypi/common-hal/busio/SPI.c msgid "SPI peripheral in use" -msgstr "" +msgstr "Periférico SPI en uso" #: shared-bindings/audiomixer/Mixer.c msgid "Sample rate must be positive" @@ -1941,14 +2030,6 @@ msgstr "Frecuencia de muestreo demasiado alta. Debe ser menor a %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "Escaneo en progreso. Usa stop_scan para detener." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "Pin CTS seleccionado no válido" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "Pin RTS seleccionado no válido" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1960,11 +2041,11 @@ msgstr "El contexto del lado del servidor no puede tener un hostname" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Set pin count must be between 1 and 5" -msgstr "" +msgstr "La suma de pines configurados debe estar entre 1 y 5" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Side set pin count must be between 1 and 5" -msgstr "" +msgstr "El conteo de pines de Side set debe estar entre 1 y 5" #: ports/cxd56/common-hal/camera/Camera.c msgid "Size not supported" @@ -1997,6 +2078,14 @@ msgstr "Dividiendo con sub-capturas" msgid "Stack size must be at least 256" msgstr "El tamaño de la pila debe ser de al menos 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "Estéreo izquierdo debe estar en el canal PWM A" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "Estéreo derecho debe estar en el canal PWM B" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "A Stream le falta el método readinto() o write()." @@ -2007,7 +2096,7 @@ msgstr "Suministre al menos un pin UART" #: shared-bindings/alarm/time/TimeAlarm.c msgid "Supply one of monotonic_time or epoch_time" -msgstr "" +msgstr "Suministre monotonic_time o epoch_time" #: shared-bindings/gnss/GNSS.c msgid "System entry must be gnss.SatelliteSystem" @@ -2043,11 +2132,10 @@ msgid "" "enough power for the whole circuit and press reset (after ejecting " "CIRCUITPY).\n" msgstr "" -"La alimentación del microntrolador cayó. Asegúrate que tu fuente de " +"La alimentación del microntrolador bajó. Asegúrate que tu fuente de " "alimentación\n" "pueda aportar suficiente energía para todo el circuito y presiona reset " -"(luego de\n" -"expulsar CIRCUITPY)\n" +"(luego de expulsar CIRCUITPY)\n" #: shared-module/audiomixer/MixerVoice.c msgid "The sample's bits_per_sample does not match the mixer's" @@ -2083,7 +2171,7 @@ msgstr "Ancho del Tile debe dividir exactamente el ancho de mapa de bits" #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." -msgstr "" +msgstr "Tiempo suministrado esta en el pasado." #: ports/nrf/common-hal/_bleio/Adapter.c #, c-format @@ -2092,18 +2180,12 @@ msgstr "" "Tiempo de espera demasiado largo: El tiempo máximo de espera es de %d " "segundos" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" -"El temporizador es utilizado para uso interno - declare los pines para PWM " -"más temprano en el programa" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Para salir, por favor reinicia la tarjeta sin " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Demasiados canales en sample." @@ -2116,9 +2198,8 @@ msgid "Too many displays" msgstr "Muchos displays" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "" -"Los datos totales a escribir son más grandes que outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "La cantidad total de datos es mas grande que %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2144,10 +2225,6 @@ msgstr "Error de inicialización de UART" msgid "UART Re-init error" msgstr "Error de reinicialización de UART" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "Error de escritura UART" @@ -2174,6 +2251,8 @@ msgstr "UUID valor no es un str, int o byte buffer" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "No se pudieron asignar buffers para la conversión con signo" @@ -2205,13 +2284,13 @@ msgstr "Imposible escribir en nvm." #: shared-bindings/alarm/SleepMemory.c msgid "Unable to write to sleep_memory." -msgstr "" +msgstr "Imposible de escribir en sleep_memory." #: ports/nrf/common-hal/_bleio/UUID.c msgid "Unexpected nrfx uuid type" msgstr "Tipo de uuid nrfx inesperado" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "Error no manejado de ESP TLS %d %d %x %d" @@ -2219,7 +2298,7 @@ msgstr "Error no manejado de ESP TLS %d %d %x %d" #: shared-bindings/wifi/Radio.c #, c-format msgid "Unknown failure %d" -msgstr "" +msgstr "Fallo desconocido %d" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format @@ -2237,8 +2316,8 @@ msgstr "Error de seguridad desconocido: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Error leve desconocido en dispositivo: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "Error desconocido en el firmware sistema: %04x" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2267,7 +2346,7 @@ msgstr "Sin capacidad de bus tipo display" msgid "Unsupported format" msgstr "Formato no soportado" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Operación no soportada" @@ -2277,7 +2356,7 @@ msgstr "valor pull no soportado." #: ports/esp32s2/common-hal/dualbank/__init__.c msgid "Update Failed" -msgstr "" +msgstr "La actualización fallo" #: ports/nrf/common-hal/_bleio/Characteristic.c #: ports/nrf/common-hal/_bleio/Descriptor.c @@ -2291,11 +2370,7 @@ msgstr "Tamaño de valor > max_length" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "Version was invalid" -msgstr "" - -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "funciones Viper no soportan por el momento, más de 4 argumentos" +msgstr "La versión era invalida" #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" @@ -2351,7 +2426,7 @@ msgstr "La clave de WiFi debe ser entre 8 y 63 caracteres" #: main.c msgid "Woken up by alarm.\n" -msgstr "" +msgstr "Despertado por la alarma.\n" #: ports/nrf/common-hal/_bleio/PacketBuffer.c msgid "Writes not supported on Characteristic" @@ -2385,11 +2460,6 @@ msgstr "se requiere un objeto bytes-like" msgid "abort() called" msgstr "se llamó abort()" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "la dirección %08x no esta alineada a %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "address fuera de límites" @@ -2398,15 +2468,19 @@ msgstr "address fuera de límites" msgid "addresses is empty" msgstr "addresses esta vacío" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "argumento es una secuencia vacía" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "El argumento para argsort debe ser un ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "El argot no está implementado para arrays aplanados" @@ -2414,10 +2488,6 @@ msgstr "El argot no está implementado para arrays aplanados" msgid "argument has wrong type" msgstr "el argumento tiene un tipo erroneo" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "argumento debe ser ndarray" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2427,7 +2497,8 @@ msgstr "argumento número/tipos no coinciden" msgid "argument should be a '%q' not a '%q'" msgstr "argumento deberia ser un '%q' no un '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "argumentos deben ser ndarrays" @@ -2440,11 +2511,11 @@ msgstr "Longitud del array e índice tienen que ser iguales" msgid "array/bytes required on right side" msgstr "array/bytes requeridos en el lado derecho" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "Intendo de obteber (arg)min/(arg)max de secuencia vacía" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "intento de obtener argmin/argmax de una secuencia vacía" @@ -2452,15 +2523,15 @@ msgstr "intento de obtener argmin/argmax de una secuencia vacía" msgid "attributes not supported yet" msgstr "atributos aún no soportados" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "Eje está fuera de sus límites" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "Eje tiene que ser None, o un entero" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "Eje demasiado largo" @@ -2485,8 +2556,8 @@ msgid "binary op %q not implemented" msgstr "operacion binaria %q no implementada" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bits deben ser 7, 8 ó 9" +msgid "bits must be in range 5 to 9" +msgstr "los bits deben estar en el rango de 5 a 9" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2496,17 +2567,13 @@ msgstr "bits_per_sample debe ser 8 ó 16" msgid "branch not in range" msgstr "la rama no está dentro del rango" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" -msgstr "" +msgstr "El buffer es mas pequeño que el requerido" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer debe de ser un objeto bytes-like" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" -msgstr "" +msgstr "El tamaño del buffer debe ser un múltiplo del tamaño del elemento" #: shared-module/struct/__init__.c msgid "buffer size must match format" @@ -2521,7 +2588,7 @@ msgstr "Las secciones del buffer necesitan tener longitud igual" msgid "buffer too small" msgstr "buffer demasiado pequeño" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "búfer muy pequeño para los bytes solicitados" @@ -2587,6 +2654,10 @@ msgstr "no se puede asignar a la expresión" msgid "can't convert %q to %q" msgstr "no puede convertir %q a %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "no se puede convertir el objeto '%q' a %q implícitamente" @@ -2595,6 +2666,10 @@ msgstr "no se puede convertir el objeto '%q' a %q implícitamente" msgid "can't convert to %q" msgstr "no puede convertir a %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "no se puede convertir a int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "no se puede convertir a str implícitamente" @@ -2718,9 +2793,13 @@ msgstr "El argumento de chr() no esta en el rango(256)" msgid "circle can only be registered in one parent" msgstr "circulo solo puede ser registrado con un pariente" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "El punto de recorte debe ser una tupla (x, y)" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" -msgstr "" +msgstr "código fuera del rango 0~127" #: shared-bindings/displayio/Palette.c msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" @@ -2762,19 +2841,19 @@ msgstr "constant debe ser un entero" msgid "conversion to object" msgstr "conversión a objeto" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "los argumentos para convolve deben ser arreglos lineares" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "los argumentos para convolve deben ser ndarrays" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "los argumentos para convolve no deben estar vacíos" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "no se pudo invertir la matriz de Vandermonde" @@ -2782,21 +2861,21 @@ msgstr "no se pudo invertir la matriz de Vandermonde" msgid "couldn't determine SD card version" msgstr "no se pudo determinar la versión de la tarjeta SD" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "Cruce está definido para un array 1D de longitud 3" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "los datos deben permitir iteración" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "los datos deben ser de igual tamaño" #: extmod/ulab/code/ndarray.c msgid "data type not understood" -msgstr "" +msgstr "tipo de dato no comprendido" #: py/parsenum.c msgid "decimal numbers not supported" @@ -2808,7 +2887,7 @@ msgstr "'except' por defecto deberia estar de último" #: shared-bindings/msgpack/__init__.c msgid "default is not a function" -msgstr "" +msgstr "default no es una función" #: shared-bindings/audiobusio/PDMIn.c msgid "" @@ -2829,14 +2908,18 @@ msgstr "destination_length debe ser un int >= 0" msgid "dict update sequence has wrong length" msgstr "la secuencia de actualizacion del dict tiene una longitud incorrecta" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "El argumento diff debe ser un ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "Orden de diferenciación fuera de rango" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "las dimensiones no concuerdan" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2868,7 +2951,7 @@ msgstr "end_x debe ser un int" #: shared-bindings/alarm/time/TimeAlarm.c msgid "epoch_time not supported on this board" -msgstr "" +msgstr "epoch_time no esta soportado en esta tarjeta" #: ports/nrf/common-hal/busio/UART.c #, c-format @@ -2913,7 +2996,7 @@ msgstr "esperando la clave:valor para dict" #: shared-bindings/msgpack/__init__.c msgid "ext_hook is not a function" -msgstr "" +msgstr "ext_hook no es una función" #: py/argcheck.c msgid "extra keyword arguments given" @@ -2944,7 +3027,7 @@ msgid "f-string: single '}' is not allowed" msgstr "cadena-f: solo '}' no está permitido" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "el archivo deberia ser una archivo abierto en modo byte" @@ -2952,11 +3035,11 @@ msgstr "el archivo deberia ser una archivo abierto en modo byte" msgid "filesystem must provide mount method" msgstr "sistema de archivos debe proporcionar método de montaje" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "se debe poder llamar al primer argumento" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "el primer argumento debe ser una función" @@ -2964,11 +3047,7 @@ msgstr "el primer argumento debe ser una función" msgid "first argument must be a tuple of ndarrays" msgstr "Primer argumento tiene que ser una tupla de ndarrays" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "el primer argumento debe ser un iterable" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "el primer argumento debe ser ndarray" @@ -2980,7 +3059,7 @@ msgstr "primer argumento para super() debe ser de tipo" msgid "flattening order must be either 'C', or 'F'" msgstr "el orden de aplanamiento debe ser 'C' o 'F'" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "el argumento invertido debe ser un ndarray" @@ -3001,8 +3080,8 @@ msgid "full" msgstr "lleno" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "la función no tiene argumentos por palabra clave" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3013,7 +3092,7 @@ msgstr "la función esperaba minimo %d argumentos, tiene %d" msgid "function got multiple values for argument '%q'" msgstr "la función tiene múltiples valores para el argumento '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "la función tiene el mismo signo a extremos del intervalo" @@ -3056,6 +3135,10 @@ msgstr "generador ya se esta ejecutando" msgid "generator ignored GeneratorExit" msgstr "generador ignorado GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic debe ser 2048 bytes de largo" @@ -3088,8 +3171,9 @@ msgstr "relleno (padding) incorrecto" msgid "index is out of bounds" msgstr "el índice está fuera de límites" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "index fuera de rango" @@ -3101,7 +3185,7 @@ msgstr "indices deben ser enteros" msgid "indices must be integers, slices, or Boolean lists" msgstr "los índices deben ser enteros, particiones o listas de booleanos" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "los valores iniciales deben permitir iteración" @@ -3119,9 +3203,9 @@ msgstr "Formas de entrada y salida no son compactibles" #: extmod/ulab/code/ulab_create.c msgid "input argument must be an integer, a tuple, or a list" -msgstr "" +msgstr "argumento de entrada debe ser un entero, una tupla o una lista" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "el tamaño del arreglo de entrada debe ser potencia de 2" @@ -3129,15 +3213,15 @@ msgstr "el tamaño del arreglo de entrada debe ser potencia de 2" msgid "input arrays are not compatible" msgstr "Arrays de entrada no son compactibles" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "los datos de entrada deben ser iterables" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "la matriz de entrada es asimétrica" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "la matriz de entrada es singular" @@ -3153,23 +3237,23 @@ msgstr "Entrada tiene que ser un tensor de rango 2" msgid "input must be an ndarray" msgstr "Entrada tiene que ser un ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "Entrada tiene que ser unidimensional" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "la entrada debe ser una matriz cuadrada" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "la entrada debe ser una tupla, lista, rango o ndarray" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "los vectores de entrada deben ser de igual tamaño" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "Entradas no son iterables" @@ -3181,7 +3265,7 @@ msgstr "int() arg 2 debe ser >= 2 y <= 36" msgid "integer required" msgstr "Entero requerido" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "interp está definido para arreglos de 1D del mismo tamaño" @@ -3194,14 +3278,33 @@ msgstr "el intervalo debe ser der rango %s-%s" msgid "invalid arguments" msgstr "argumentos inválidos" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "los bits_per_pixel %d no son validos, deben ser 1, 4, 8, 16, 24 o 32" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "certificado inválido" +#: py/compile.c +msgid "invalid decorator" +msgstr "decorador invalido" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "index dupterm inválido" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "el tamaño del elemento no es valido%d por bits_per_pixel %d\n" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "el element_size %d,no es valido, debe ser 1,2 ó 4" + #: extmod/modframebuf.c msgid "invalid format" msgstr "formato inválido" @@ -3243,10 +3346,6 @@ msgstr "sintaxis inválida para entero con base %d" msgid "invalid syntax for number" msgstr "sintaxis inválida para número" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 debe ser una clase" @@ -3255,11 +3354,7 @@ msgstr "issubclass() arg 1 debe ser una clase" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass() arg 2 debe ser una clase o tuple de clases" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "los iterables no son del mismo tamaño" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "las iteraciones no convergen" @@ -3330,11 +3425,7 @@ msgstr "map buffer muy pequeño" msgid "math domain error" msgstr "error de dominio matemático" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "las dimensiones de la matriz no coinciden" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "matrix no es definida positiva" @@ -3346,7 +3437,7 @@ msgstr "max_length debe ser 0-%d cuando fixed_length es %s" #: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c msgid "max_length must be >= 0" -msgstr "" +msgstr "max_length debe ser >= 0" #: extmod/ulab/code/ndarray.c msgid "maximum number of dimensions is 4" @@ -3356,17 +3447,17 @@ msgstr "Máximo número de dimensiones es 4" msgid "maximum recursion depth exceeded" msgstr "profundidad máxima de recursión excedida" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "maxiter tiene que ser > 0" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "maxiter debe ser > 0" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" -msgstr "" +msgstr "argumento median debe ser una matriz ndarray" #: py/runtime.c #, c-format @@ -3377,11 +3468,16 @@ msgstr "la asignación de memoria falló, asignando %u bytes" msgid "memory allocation failed, heap is locked" msgstr "la asignación de memoria falló, el heap está bloqueado" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" +"memoryview: la longitud no es un múltiplo del tamaño del elemento (itemsize)" + #: py/builtinimport.c msgid "module not found" msgstr "módulo no encontrado" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "más grados de libertad que los puntos de datos" @@ -3426,6 +3522,10 @@ msgstr "yield nativo" msgid "need more than %d values to unpack" msgstr "necesita más de %d valores para descomprimir" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "potencia negativa sin float support" @@ -3452,7 +3552,7 @@ msgstr "no se ha encontrado ningún enlace para nonlocal" #: shared-module/msgpack/__init__.c msgid "no default packer" -msgstr "" +msgstr "no hay empaquetador por defecto" #: py/builtinimport.c msgid "no module named '%q'" @@ -3495,15 +3595,11 @@ msgstr "" #: ports/nrf/common-hal/_bleio/Adapter.c msgid "non-zero timeout must be > 0.01" -msgstr "" +msgstr "el tiempo de espera non-zero deber ser > 0.01" #: shared-bindings/_bleio/Adapter.c msgid "non-zero timeout must be >= interval" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "norma está definida para arrays 1D y 2D" +msgstr "el tiempo de espera non-zero debe ser >= intervalo" #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" @@ -3524,7 +3620,7 @@ msgstr "el número de puntos debe ser al menos 2" #: py/builtinhelp.c msgid "object " -msgstr "" +msgstr "objecto " #: py/obj.c msgid "object '%q' is not a tuple or list" @@ -3574,17 +3670,17 @@ msgstr "objeto con protocolo de buffer requerido" msgid "odd-length string" msgstr "string de longitud impar" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "offset es demasiado grande" #: shared-bindings/dualbank/__init__.c msgid "offset must be >= 0" -msgstr "" +msgstr "offset debe ser >= 0" #: extmod/ulab/code/ulab_create.c msgid "offset must be non-negative and no greater than buffer length" -msgstr "" +msgstr "offset debe ser non-negative y no mayo que la longitud del buffer" #: py/objstr.c py/objstrunicode.c msgid "offset out of bounds" @@ -3603,8 +3699,8 @@ msgstr "solo se admite sample_rate=16000" msgid "only slices with step=1 (aka None) are supported" msgstr "solo se admiten segmentos con step=1 (alias None)" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "los operandos no se pueden transmitir juntos" @@ -3612,7 +3708,7 @@ msgstr "los operandos no se pueden transmitir juntos" msgid "operation is implemented for 1D Boolean arrays only" msgstr "operación solo está implementada para arrays booleanos de 1D" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "la operación no está implementada para ndarrays" @@ -3629,11 +3725,19 @@ msgstr "ord espera un carácter" msgid "ord() expected a character, but string of length %d found" msgstr "ord() espera un carácter, pero encontró un string de longitud %d" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "La matriz de salida es demasiado pequeña" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "la matriz de salida debe ser densa de números float" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "fuera de rango de fuente" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "fuera de rango del objetivo" @@ -3654,10 +3758,6 @@ msgstr "palette debe ser 32 bytes de largo" msgid "palette_index should be an int" msgstr "palette_index deberia ser un int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parámetro de anotación debe ser un identificador" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "los parámetros deben ser registros en secuencia de a2 a a5" @@ -3666,7 +3766,7 @@ msgstr "los parámetros deben ser registros en secuencia de a2 a a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "los parametros deben ser registros en secuencia del r0 al r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "coordenadas del pixel fuera de límites" @@ -3689,11 +3789,16 @@ msgstr "pop de un PulseIn vacío" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "pop desde %q vacía" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "port debe ser be >= 0" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "el 3er argumento de pow() no puede ser 0" @@ -3704,12 +3809,17 @@ msgstr "pow() con 3 argumentos requiere enteros" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3717,6 +3827,7 @@ msgstr "pow() con 3 argumentos requiere enteros" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "presionando botón de arranque al inicio.\n" @@ -3728,13 +3839,21 @@ msgstr "presionando botón de arranque al inicio.\n" msgid "pressing both buttons at start up.\n" msgstr "presionando ambos botones al inicio.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "presione el botón izquierdo al arranque\n" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "máscara de pull en conflicto con máscara de dirección" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" -msgstr "" +msgstr "pull_threshold debe esta entre 1 y 32" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "push_threshold must be between 1 and 32" -msgstr "" +msgstr "push_threshold debe esta entre 1 y 32" #: extmod/modutimeq.c msgid "queue overflow" @@ -3744,7 +3863,7 @@ msgstr "desbordamiento de cola(queue)" msgid "raw f-strings are not implemented" msgstr "no está implementado cadenas-f sin procesar" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "las partes reales e imaginarias deben ser de igual longitud" @@ -3779,7 +3898,7 @@ msgstr "rgb_pins[%d] duplica otra asignación de pin" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins[%d] no está en el mismo puerto que el reloj" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "Argumento enrolado tiene que ser un ndarray" @@ -3796,6 +3915,7 @@ msgstr "" "o'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "frecuencia de muestreo fuera de rango" @@ -3813,7 +3933,7 @@ msgstr "forma tiene que ser una tupla" #: shared-module/msgpack/__init__.c msgid "short read" -msgstr "" +msgstr "lectura corta" #: py/objstr.c msgid "sign not allowed in string format specifier" @@ -3827,7 +3947,7 @@ msgstr "signo no permitido con el especificador integer format 'c'" msgid "single '}' encountered in format string" msgstr "un solo '}' encontrado en format string" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "el tamaño se define solo para ndarrays" @@ -3851,23 +3971,23 @@ msgstr "pequeño int desbordamiento" msgid "soft reboot\n" msgstr "reinicio suave\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "argumento de ordenado debe ser un ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "el arreglo sos debe de forma (n_section, 6)" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "sos[:, 3] deberían ser todos unos" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "sosfilt requiere argumentos iterables" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "paleta fuente muy larga" @@ -3933,7 +4053,7 @@ msgstr "limite debe ser en el rango 0-65536" #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "tile must be greater than zero" -msgstr "" +msgstr "tile debe sera mas grande que cero" #: shared-bindings/time/__init__.c msgid "time.struct_time() takes a 9-sequence" @@ -3952,7 +4072,7 @@ msgstr "el tiempo de espera debe ser 0.0-100.0 segundos" #: ports/nrf/common-hal/_bleio/Adapter.c msgid "timeout must be < 655.35 secs" -msgstr "" +msgstr "timeout debe ser < 655.35 segundos" #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "timeout must be >= 0.0" @@ -3978,9 +4098,9 @@ msgstr "tobytes solo pueden ser invocados por arrays densos" msgid "too many arguments provided with the given format" msgstr "demasiados argumentos provistos con el formato dado" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" -msgstr "" +msgstr "demasiadas dimensiones" #: extmod/ulab/code/ndarray.c msgid "too many indices" @@ -3991,18 +4111,14 @@ msgstr "demasiados índices" msgid "too many values to unpack (expected %d)" msgstr "demasiados valores para descomprimir (%d esperado)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" -msgstr "" +msgstr "trapz esta definido para matrices 1D" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "trapz está definido para arreglos 1D de igual tamaño" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupla/lista tiene una longitud incorrecta" @@ -4084,7 +4200,7 @@ msgstr "formato de código desconocicdo '%c' para objeto de tipo '%q'" msgid "unknown type" msgstr "tipo desconocido" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "tipo desconocido '%q'" @@ -4137,14 +4253,6 @@ msgstr "el valor debe caber en %d byte(s)" msgid "value_count must be > 0" msgstr "value_count debe ser > 0" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "los vectores deben tener el mismo tamaño" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "watchdog no inicializado" @@ -4153,19 +4261,24 @@ msgstr "watchdog no inicializado" msgid "watchdog timeout must be greater than 0" msgstr "el tiempo de espera del perro guardián debe ser mayor a 0" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "ancho debe estar entre 2 y 8 (inclusivamente), no %d" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "el ancho debe ser mayor que cero" #: ports/esp32s2/common-hal/wifi/Radio.c msgid "wifi is not enabled" -msgstr "" +msgstr "wifi no esta habilitado" #: shared-bindings/_bleio/Adapter.c msgid "window must be <= interval" msgstr "la ventana debe ser <= intervalo" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "indice de eje erróneo" @@ -4173,7 +4286,8 @@ msgstr "indice de eje erróneo" msgid "wrong axis specified" msgstr "eje especificado erróneo" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "tipo de entrada incorrecta" @@ -4189,7 +4303,7 @@ msgstr "numero erroneo de valores a descomprimir" msgid "wrong operand type" msgstr "tipo de operando incorrecto" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "tipo de salida incorrecta" @@ -4199,7 +4313,7 @@ msgstr "valor x fuera de límites" #: ports/esp32s2/common-hal/audiobusio/__init__.c msgid "xTaskCreate failed" -msgstr "" +msgstr "fallo en xTaskCreate" #: shared-bindings/displayio/Shape.c msgid "y should be an int" @@ -4213,18 +4327,151 @@ msgstr "valor y fuera de límites" msgid "zero step" msgstr "paso cero" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "zi debe ser un ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "zi debe ser de tipo flotante" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "zi debe ser una forma (n_section,2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "funciones Viper no soportan por el momento, más de 4 argumentos" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "la dirección %08x no esta alineada a %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "la función no tiene argumentos por palabra clave" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parámetro de anotación debe ser un identificador" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Los datos totales a escribir son más grandes que outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 y 4 no soportan pullup interno durante sleep" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer debe de ser un objeto bytes-like" + +#~ msgid "io must be rtc io" +#~ msgstr "io debe ser rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "nivel de accionamiento debe ser 0 o 1" + +#~ msgid "wakeup conflict" +#~ msgstr "conflicto de wakeup" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "Se intentó asignación del montículo, sin que la VM de MicroPython esté " +#~ "ejecutando." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR jump falló. Probable corrupción de la memoria." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Error fatal de MicroPython." + +#~ msgid "argument must be ndarray" +#~ msgstr "argumento debe ser ndarray" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "las dimensiones de la matriz no coinciden" + +#~ msgid "norm is defined for 1D and 2D arrays" +#~ msgstr "norma está definida para arrays 1D y 2D" + +#~ msgid "vectors must have same lengths" +#~ msgstr "los vectores deben tener el mismo tamaño" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Fallo de aserción de dispositivo Nordic Soft." + +#~ msgid "Nordic soft device out of memory" +#~ msgstr "El firmaware del sistema no tiene memoria" + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Error leve desconocido en dispositivo: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "el primer argumento debe ser un iterable" + +#~ msgid "iterables are not of the same length" +#~ msgstr "los iterables no son del mismo tamaño" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Pin CTS seleccionado no válido" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Pin RTS seleccionado no válido" + +#~ msgid "Could not initialize channel" +#~ msgstr "No se pudo inicializar el canal" + +#~ msgid "Could not initialize timer" +#~ msgstr "No se pudo inicializar el temporizador" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Frecuencia suministrada no válida" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Pines inválidos para PWMOut" + +#~ msgid "No more channels available" +#~ msgstr "No hay más canales disponibles" + +#~ msgid "No more timers available" +#~ msgstr "No hay más temporizadores disponibles" + +#~ msgid "No more timers available on this pin." +#~ msgstr "No hay más temporizadores disponibles en este pin." + +#~ msgid "" +#~ "Timer was reserved for internal use - declare PWM pins earlier in the " +#~ "program" +#~ msgstr "" +#~ "El temporizador es utilizado para uso interno - declare los pines para " +#~ "PWM más temprano en el programa" + +#~ msgid "Group full" +#~ msgstr "Group lleno" + +#~ msgid "In buffer elements must be 4 bytes long or less" +#~ msgstr "" +#~ "Los elementos del búfer de entrada deben ser de una longitud de 4 bytes o " +#~ "menos" + +#~ msgid "Out buffer elements must be 4 bytes long or less" +#~ msgstr "" +#~ "Los elementos del búfer de salida deben ser de una longitud de 4 bytes o " +#~ "menos" + +#~ msgid "Initial set pin direcion conflicts with initial out pin direction" +#~ msgstr "" +#~ "La dirección inicial del pin de configuración esta en conflicto con la " +#~ "dirección de salida inicial del pin" + +#~ msgid "UART not yet supported" +#~ msgstr "UART no esta soportado todavia" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bits deben ser 7, 8 ó 9" + +#~ msgid "Only IN/OUT of up to 8 supported" +#~ msgstr "Solamente IN/OUT hasta 8 esta soportado" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA o SCL necesitan una pull up" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "" #~ "%d pines de dirección y %d pines rgb indican una altura de %d, no de %d" @@ -4399,9 +4646,6 @@ msgstr "zi debe ser una forma (n_section,2)" #~ msgid "can't convert to float" #~ msgstr "no se puede convertir a float" -#~ msgid "can't convert to int" -#~ msgstr "no se puede convertir a int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "el objeto '%s' no es una tupla o lista" diff --git a/locale/fil.po b/locale/fil.po index bba9761ad97c0..aa1badbfaf617 100644 --- a/locale/fil.po +++ b/locale/fil.po @@ -72,6 +72,7 @@ msgstr "%q ay ginagamit" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -102,6 +103,7 @@ msgstr "aarehas na haba dapat ang buffer slices" msgid "%q must be a tuple of length 2" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "" @@ -334,10 +336,15 @@ msgid "All SPI peripherals are in use" msgstr "Lahat ng SPI peripherals ay ginagamit" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c #, fuzzy msgid "All UART peripherals are in use" msgstr "Lahat ng I2C peripherals ginagamit" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Lahat ng event channels ginagamit" @@ -366,6 +373,7 @@ msgstr "Lahat ng timers para sa pin na ito ay ginagamit" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Lahat ng timer ginagamit" @@ -406,6 +414,10 @@ msgstr "AnalogOut ay 16 bits. Value ay dapat hindi hihigit pa sa 65536." msgid "AnalogOut not supported on given pin" msgstr "Hindi supportado ang AnalogOut sa ibinigay na pin" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -429,7 +441,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -457,6 +469,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Ang bit clock at word select dapat makibahagi sa isang clock unit" @@ -498,6 +514,10 @@ msgstr "" msgid "Buffer + offset too small %d %d %d" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -514,6 +534,7 @@ msgid "Buffer is too small" msgstr "" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "" @@ -543,6 +564,7 @@ msgstr "" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, fuzzy, c-format msgid "Bus pin %d is already in use" msgstr "Ginagamit na ang DAC" @@ -636,6 +658,10 @@ msgstr "Hindi ma-remount '/' kapag aktibo ang USB." msgid "Cannot reset into bootloader because no bootloader is present." msgstr "Hindi ma-reset sa bootloader dahil walang bootloader." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Hindi ma i-set ang value kapag ang direksyon ay input." @@ -657,7 +683,7 @@ msgstr "Hindi maaaring ilipat kapag walang MOSI at MISO pin." msgid "Cannot unambiguously get sizeof scalar" msgstr "Hindi puedeng hindi sigurado ang get sizeof scalar" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" @@ -740,14 +766,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "Hindi ma-initialize ang UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "" @@ -768,7 +786,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "" @@ -872,11 +890,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Ginagamit na ang EXTINT channel" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "May pagkakamali sa REGEX" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -929,15 +952,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -951,6 +974,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Nabigo sa pag kuha ng mutex, status: 0x%08lX" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Nabigong ilaan ang RX buffer" @@ -959,6 +983,7 @@ msgstr "Nabigong ilaan ang RX buffer" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -972,6 +997,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "" @@ -997,6 +1026,10 @@ msgstr "Nabigo sa pagrelease ng mutex, status: 0x%08lX" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Mayroong file" @@ -1020,7 +1053,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1039,10 +1072,6 @@ msgstr "" msgid "Group already used" msgstr "" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Puno ang group" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1073,15 +1102,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1098,10 +1127,23 @@ msgstr "" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1158,6 +1200,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Mali ang %q pin" @@ -1184,8 +1227,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Mali ang PWM frequency" @@ -1203,7 +1252,8 @@ msgstr "Maling argumento" msgid "Invalid bits per value" msgstr "" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Mali ang buffer size" @@ -1232,14 +1282,10 @@ msgstr "Mali ang file" msgid "Invalid format chunk size" msgstr "Mali ang format ng chunk size" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "" @@ -1278,17 +1324,13 @@ msgstr "Mali ang pin para sa kanang channel" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Mali ang pins" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1310,7 +1352,7 @@ msgstr "" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1318,10 +1360,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1334,14 +1372,11 @@ msgstr "Maling bilang ng voice" msgid "Invalid wave file" msgstr "May hindi tama sa wave file" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "" @@ -1387,14 +1422,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Ang delay ng startup ng mikropono ay dapat na nasa 0.0 hanggang 1.0" @@ -1446,6 +1473,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1465,9 +1496,15 @@ msgstr "Walang DAC sa chip" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Walang DMA channel na mahanap" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1526,24 +1563,20 @@ msgstr "" msgid "No hardware support on pin" msgstr "Walang support sa hardware ang pin" -#: shared-bindings/aesio/aes.c -msgid "No key was specified" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" +#: shared-bindings/aesio/aes.c +msgid "No key was specified" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." +#: shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" #: shared-bindings/wifi/Radio.c @@ -1554,6 +1587,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1571,13 +1610,18 @@ msgid "No timer available" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c #, fuzzy @@ -1609,13 +1653,10 @@ msgid "Odd parity is not supported" msgstr "Odd na parity ay hindi supportado" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Tanging 8 o 16 na bit mono na may " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1665,10 +1706,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Oversample ay dapat multiple ng 8." @@ -1688,8 +1738,15 @@ msgid "" msgstr "" "PWM frequency hindi writable kapag variable_frequency ay False sa pag buo." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "" @@ -1725,6 +1782,10 @@ msgstr "Ang pin ay walang kakayahan sa ADC" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "" @@ -1741,6 +1802,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Kasama ang kung ano pang modules na sa filesystem\n" @@ -1812,6 +1881,10 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1819,6 +1892,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "RTC calibration ay hindi supportado ng board na ito" @@ -1827,7 +1901,7 @@ msgid "RTC is not supported on this board" msgstr "Hindi supportado ang RTC sa board na ito" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "" @@ -1885,12 +1959,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "Kailangan ng pull up resistors ang SDA o SCL" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1926,14 +1994,6 @@ msgstr "Sample rate ay masyadong mataas. Ito ay dapat hindi hiigit sa %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1982,6 +2042,14 @@ msgstr "Binibiyak gamit ang sub-captures" msgid "Stack size must be at least 256" msgstr "Ang laki ng stack ay dapat na hindi bababa sa 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Stream kulang ng readinto() o write() method." @@ -2066,16 +2134,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Para lumabas, paki-reset ang board na wala ang " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Sobra ang channels sa sample." @@ -2088,7 +2152,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2115,10 +2179,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "" @@ -2145,6 +2205,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Hindi ma-allocate ang buffers para sa naka-sign na conversion" @@ -2183,7 +2245,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "hindi inaasahang indent" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2209,7 +2271,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2238,7 +2300,7 @@ msgstr "Hindi supportadong tipo ng bitmap" msgid "Unsupported format" msgstr "Hindi supportadong format" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Hindi sinusuportahang operasyon" @@ -2264,12 +2326,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" -"Ang mga function ng Viper ay kasalukuyang hindi sumusuporta sa higit sa 4 na " -"argumento" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2355,11 +2411,6 @@ msgstr "a bytes-like object ay kailangan" msgid "abort() called" msgstr "abort() tinawag" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "address %08x ay hindi pantay sa %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "wala sa sakop ang address" @@ -2368,15 +2419,19 @@ msgstr "wala sa sakop ang address" msgid "addresses is empty" msgstr "walang laman ang address" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg ay walang laman na sequence" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2384,10 +2439,6 @@ msgstr "" msgid "argument has wrong type" msgstr "may maling type ang argument" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2397,7 +2448,8 @@ msgstr "hindi tugma ang argument num/types" msgid "argument should be a '%q' not a '%q'" msgstr "argument ay dapat na '%q' hindi '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2410,11 +2462,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "array/bytes kinakailangan sa kanang bahagi" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2422,15 +2474,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "attributes hindi sinusuportahan" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2455,8 +2507,8 @@ msgid "binary op %q not implemented" msgstr "binary op %q hindi implemented" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bits ay dapat 7, 8 o 9" +msgid "bits must be in range 5 to 9" +msgstr "" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2466,15 +2518,11 @@ msgstr "bits_per_sample ay dapat 8 o 16" msgid "branch not in range" msgstr "branch wala sa range" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer ay dapat bytes-like object" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2492,7 +2540,7 @@ msgstr "aarehas na haba dapat ang buffer slices" msgid "buffer too small" msgstr "masyadong maliit ang buffer" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2559,6 +2607,10 @@ msgstr "hindi ma i-assign sa expression" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "hindi maaaring i-convert ang '%q' na bagay sa %q nang walang pahiwatig" @@ -2567,6 +2619,10 @@ msgstr "hindi maaaring i-convert ang '%q' na bagay sa %q nang walang pahiwatig" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "hindi ma-convert sa int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "hindi ma i-convert sa string ng walang pahiwatig" @@ -2690,6 +2746,10 @@ msgstr "chr() arg wala sa sakop ng range(256)" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2734,19 +2794,19 @@ msgstr "constant ay dapat na integer" msgid "conversion to object" msgstr "kombersyon to object" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2754,15 +2814,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2803,14 +2863,18 @@ msgstr "ang destination_length ay dapat na isang int >= 0" msgid "dict update sequence has wrong length" msgstr "may mali sa haba ng dict update sequence" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2919,7 +2983,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "file ay dapat buksan sa byte mode" @@ -2927,11 +2991,11 @@ msgstr "file ay dapat buksan sa byte mode" msgid "filesystem must provide mount method" msgstr "ang filesystem dapat mag bigay ng mount method" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2939,11 +3003,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2955,7 +3015,7 @@ msgstr "unang argument ng super() ay dapat type" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2976,8 +3036,8 @@ msgid "full" msgstr "puno" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "ang function ay hindi kumukuha ng mga argumento ng keyword" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -2988,7 +3048,7 @@ msgstr "function na inaasahang %d ang argumento, ngunit %d ang nakuha" msgid "function got multiple values for argument '%q'" msgstr "ang function ay nakakuha ng maraming values para sa argument '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -3032,6 +3092,10 @@ msgstr "insinasagawa na ng generator" msgid "generator ignored GeneratorExit" msgstr "hindi pinansin ng generator ang GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic ay dapat 2048 bytes ang haba" @@ -3064,8 +3128,9 @@ msgstr "mali ang padding" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "index wala sa sakop" @@ -3077,7 +3142,7 @@ msgstr "ang mga indeks ay dapat na integer" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3097,7 +3162,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3105,15 +3170,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3129,23 +3194,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3157,7 +3222,7 @@ msgstr "int() arg 2 ay dapat >=2 at <= 36" msgid "integer required" msgstr "kailangan ng int" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3170,14 +3235,33 @@ msgstr "" msgid "invalid arguments" msgstr "mali ang mga argumento" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "mali ang cert" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "mali ang dupterm index" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "hindi wastong pag-format" @@ -3219,10 +3303,6 @@ msgstr "maling sintaks sa integer na may base %d" msgid "invalid syntax for number" msgstr "maling sintaks sa number" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 ay dapat na class" @@ -3231,11 +3311,7 @@ msgstr "issubclass() arg 1 ay dapat na class" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass() arg 2 ay dapat na class o tuple ng classes" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3307,11 +3383,7 @@ msgstr "masyadong maliit ang buffer map" msgid "math domain error" msgstr "may pagkakamali sa math domain" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3333,15 +3405,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "lumagpas ang maximum recursion depth" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3354,11 +3426,15 @@ msgstr "nabigo ang paglalaan ng memorya, paglalaan ng %u bytes" msgid "memory allocation failed, heap is locked" msgstr "abigo ang paglalaan ng memorya, ang heap ay naka-lock" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "module hindi nakita" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3403,6 +3479,10 @@ msgstr "native yield" msgid "need more than %d values to unpack" msgstr "kailangan ng higit sa %d na halaga upang i-unpack" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negatibong power na walang float support" @@ -3476,10 +3556,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3548,7 +3624,7 @@ msgstr "object na may buffer protocol kinakailangan" msgid "odd-length string" msgstr "odd-length string" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3578,8 +3654,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "ang mga slices lamang na may hakbang = 1 (aka None) ang sinusuportahan" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3587,7 +3663,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3604,11 +3680,19 @@ msgstr "ord umaasa ng character" msgid "ord() expected a character, but string of length %d found" msgstr "ord() umaasa ng character pero string ng %d haba ang nakita" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3629,10 +3713,6 @@ msgstr "ang palette ay dapat 32 bytes ang haba" msgid "palette_index should be an int" msgstr "palette_index ay dapat na int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parameter annotation ay dapat na identifier" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "ang mga parameter ay dapat na nagrerehistro sa sequence a2 hanggang a5" @@ -3641,7 +3721,7 @@ msgstr "ang mga parameter ay dapat na nagrerehistro sa sequence a2 hanggang a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "ang mga parameter ay dapat na nagrerehistro sa sequence r0 hanggang r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c #, fuzzy msgid "pixel coordinates out of bounds" msgstr "wala sa sakop ang address" @@ -3665,11 +3745,16 @@ msgstr "pop mula sa walang laman na PulseIn" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "pow() 3rd argument ay hindi maaring 0" @@ -3680,12 +3765,17 @@ msgstr "pow() na may 3 argumento kailangan ng integers" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3693,6 +3783,7 @@ msgstr "pow() na may 3 argumento kailangan ng integers" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3704,6 +3795,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3720,7 +3819,7 @@ msgstr "puno na ang pila (overflow)" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3755,7 +3854,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3772,6 +3871,7 @@ msgstr "" "'H', 'b' o'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "pagpili ng rate wala sa sakop" @@ -3803,7 +3903,7 @@ msgstr "sign hindi maari sa integer format specifier 'c'" msgid "single '}' encountered in format string" msgstr "isang '}' nasalubong sa format string" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3827,23 +3927,23 @@ msgstr "small int overflow" msgid "soft reboot\n" msgstr "malambot na reboot\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3955,7 +4055,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "masyadong maraming mga argumento na ibinigay sa ibinigay na format" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3968,18 +4068,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "masyadong maraming values para i-unpact (umaasa ng %d)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "mali ang haba ng tuple/list" @@ -4061,7 +4157,7 @@ msgstr "" msgid "unknown type" msgstr "hindi malaman ang type (unknown type)" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "hindi malaman ang type '%q'" @@ -4114,14 +4210,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4130,6 +4218,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4142,7 +4235,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4150,7 +4243,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4166,7 +4260,7 @@ msgstr "maling number ng value na i-unpack" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4192,18 +4286,44 @@ msgstr "wala sa sakop ang address" msgid "zero step" msgstr "zero step" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "" +#~ "Ang mga function ng Viper ay kasalukuyang hindi sumusuporta sa higit sa 4 " +#~ "na argumento" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "address %08x ay hindi pantay sa %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "ang function ay hindi kumukuha ng mga argumento ng keyword" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotation ay dapat na identifier" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer ay dapat bytes-like object" + +#~ msgid "Group full" +#~ msgstr "Puno ang group" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bits ay dapat 7, 8 o 9" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "Kailangan ng pull up resistors ang SDA o SCL" + #~ msgid "tuple index out of range" #~ msgstr "indeks ng tuple wala sa sakop" @@ -4269,9 +4389,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "hindi ma-convert sa float" -#~ msgid "can't convert to int" -#~ msgstr "hindi ma-convert sa int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "object '%s' ay hindi tuple o list" diff --git a/locale/fr.po b/locale/fr.po index 83af1f9f7c262..941f877fe4021 100644 --- a/locale/fr.po +++ b/locale/fr.po @@ -8,14 +8,14 @@ msgstr "" "Project-Id-Version: 0.1\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-01-30 02:32+0000\n" -"Last-Translator: Antonin ENFRUN \n" +"PO-Revision-Date: 2021-04-22 17:16+0000\n" +"Last-Translator: Hugo Dahl \n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n > 1;\n" -"X-Generator: Weblate 4.5-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -84,6 +84,7 @@ msgstr "%q en cours d'utilisation" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -113,6 +114,7 @@ msgstr "%q doit être >= 1" msgid "%q must be a tuple of length 2" msgstr "%q doit être un tuple de longueur 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q est hors de porté" @@ -343,20 +345,25 @@ msgid "All SPI peripherals are in use" msgstr "Tous les périphériques SPI sont utilisés" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Tous les périphériques UART sont utilisés" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "Tout les canaux sont utilisés" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Tous les canaux d'événements sont utilisés" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "All state machines in use" -msgstr "" +msgstr "Tous les automates finis sont utilisés" #: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "All sync event channels in use" -msgstr "Tous les canaux d'événements sync (sync event channels) sont utilisés" +msgstr "Tout les canaux d'événements sync sont utilisés" #: shared-bindings/pwmio/PWMOut.c msgid "All timers for this pin are in use" @@ -374,6 +381,7 @@ msgstr "Tous les minuteurs pour cette broche sont utilisés" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Tous les minuteurs sont utilisés" @@ -416,6 +424,10 @@ msgstr "" msgid "AnalogOut not supported on given pin" msgstr "'AnalogOut' n'est pas supporté sur la broche indiquée" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "Un autre PWMAudioOut est déjà actif" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -423,11 +435,11 @@ msgstr "Un autre envoi est déjà actif" #: shared-bindings/pulseio/PulseOut.c msgid "Array must contain halfwords (type 'H')" -msgstr "Le tableau doit contenir des demi-mots (type 'H')" +msgstr "La matrice doit contenir des demi-mots (type 'H')" #: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c msgid "Array values should be single bytes." -msgstr "Les valeurs du tableau doivent être des octets singuliers." +msgstr "Les valeurs de la matrice doivent être des octets singuliers." #: shared-bindings/microcontroller/Pin.c msgid "At most %d %q may be specified (not %d)" @@ -439,10 +451,10 @@ msgid "Attempt to allocate %d blocks" msgstr "Tentative d'allocation de %d blocs" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" -"Tentative d'allocation de segments lorsque la machine virtuelle MicroPython " -"n'est pas en cours d'exécution." +"Tentative d'allocation à la pile quand la Machine Virtuelle n'est pas en " +"exécution." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -469,6 +481,10 @@ msgstr "Baudrate non supporté par le périphérique" msgid "Below minimum frame rate" msgstr "Au-dessous de la fréquence d'images minimale" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "Bit clock et word select doivent êtres sur des broches séquentielles" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "'bit clock' et 'word select' doivent partager une horloge" @@ -510,6 +526,10 @@ msgstr "Luminosité non-ajustable" msgid "Buffer + offset too small %d %d %d" msgstr "Tampon + décalage trop petit %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Éléments du tampon doit être 4 octets ou moins" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -526,6 +546,7 @@ msgid "Buffer is too small" msgstr "Le tampon est trop petit" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "La longueur du tampon %d est trop grande. Il doit être inférieur à %d" @@ -555,6 +576,7 @@ msgstr "Tampon trop court de %d octets" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "La broche %d du bus est déjà utilisée" @@ -654,6 +676,10 @@ msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" "Ne peut être redémarré vers le bootloader car il n'y a pas de bootloader." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "Ne peut définir les options de socket" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "" @@ -676,7 +702,7 @@ msgstr "Pas de transfert sans broches MOSI et MISO." msgid "Cannot unambiguously get sizeof scalar" msgstr "Impossible d'obtenir la taille (sizeof) du scalaire sans ambigüité" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "Impossible de faire varier la fréquence sur un minuteur déjà utilisée" @@ -763,14 +789,6 @@ msgstr "Impossible d'initialiser la carte SD" msgid "Could not initialize UART" msgstr "Impossible d'initialiser UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Impossible d'initialiser le canal" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Impossible d'initialiser le minuteur" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Impossible de réinitialiser le canal" @@ -791,7 +809,7 @@ msgstr "Impossible d’obtenir l’horloge" msgid "Could not set address" msgstr "Impossible de définir l’adresse" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "Impossible de démarrer PWM" @@ -893,11 +911,16 @@ msgstr "ESP-IDF échec d'allocation de la mémoire" msgid "EXTINT channel already in use" msgstr "Canal EXTINT déjà utilisé" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Erreur dans le flot MIDI à la position %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Erreur dans l'expression régulière" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "Erreur : Impossible de lier" @@ -949,15 +972,15 @@ msgid "Extended advertisements with scan response not supported." msgstr "" "Les avertissement étendues avec analyse de réponse ne sont pas supportées." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "La FFT est définie uniquement pour les ndarrays" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" -msgstr "FFT n'est implémenté que pour les tableaux linéaires" +msgstr "FFT n'est implémenté que pour les matrices linéaires" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "Échec du handshake SSL" @@ -971,6 +994,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Echec de l'obtention de mutex, err 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Echec de l'allocation du tampon RX" @@ -979,6 +1003,7 @@ msgstr "Echec de l'allocation du tampon RX" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -992,6 +1017,10 @@ msgstr "Impossible d’allouer la mémoire pour Wifi" msgid "Failed to allocate wifi scan memory" msgstr "Impossible d'allouer la mémoire pour le scan wifi" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "Échec du tamponage de l'échantillon" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Impossible de se connecter : erreur interne" @@ -1017,6 +1046,10 @@ msgstr "Impossible de libérer mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Échec de l'écriture vers flash interne." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Erreurre fatale." + #: py/moduerrno.c msgid "File exists" msgstr "Le fichier existe" @@ -1040,7 +1073,7 @@ msgstr "Format non supporté" msgid "Framebuffer requires %d bytes" msgstr "FrameBuffer nécessite %d octets" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" "La fréquence doit correspondre à PWMOut existant à l'utilisation de ce " @@ -1061,10 +1094,6 @@ msgstr "Échec génerique" msgid "Group already used" msgstr "Groupe déjà utilisé" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Groupe plein" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1089,21 +1118,21 @@ msgstr "Erreur d'initialisation I2C" #: ports/raspberrypi/common-hal/busio/I2C.c msgid "I2C peripheral in use" -msgstr "" +msgstr "périphérique I2C utilisé" #: shared-bindings/audiobusio/I2SOut.c msgid "I2SOut not available" msgstr "I2SOut n'est pas disponible" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 & 4 ne supportent pas l'éleveuse interne en mode someil" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IV doit être de longueur de %d octets" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "Éléments dans le tampon doivent être <= à 4 octets" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1118,12 +1147,30 @@ msgstr "Taille de tampon incorrecte" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Init program size invalid" +msgstr "Taille du programme d'initialisation non valide" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" msgstr "" +"Direction initiale de \"set pin\" est en conflit avec la direction initiale " +"de \"out pin\"" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" +"État initial de \"set pin\" est en conflit avec l'état initial de \"out pin\"" #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "Échec d'initialisation par manque de mémoire" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" +"La taille (%d) du tampon d'entrée doit être un multiple du nombre (%d) de " +"brins" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "L'entrée prend trop de temps" @@ -1135,27 +1182,31 @@ msgstr "Erreur d'entrée/sortie" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d jumps on pin" -msgstr "" +msgstr "Instruction %d saute sur la broche" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts in more bits than pin count" msgstr "" +"Instruction %d décale vers l'intérieur de plus de bits que le nombre de " +"broches" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts out more bits than pin count" msgstr "" +"instruction %d décale vers l'extérieur de plus de bits que le nombre de " +"broches" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d uses extra pin" -msgstr "" +msgstr "instruction %d utilise des broches supplémentaires" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d waits on input outside of count" -msgstr "" +msgstr "instruction %d attend sur une entrée hors du compte" #: ports/nrf/common-hal/_bleio/__init__.c msgid "Insufficient authentication" @@ -1180,6 +1231,7 @@ msgstr "%q invalide" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Broche invalide pour '%q'" @@ -1206,8 +1258,14 @@ msgstr "BSSID invalide" msgid "Invalid DAC pin supplied" msgstr "Broche DAC non valide fournie" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "Fichier MIDI invalide" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Fréquence de PWM invalide" @@ -1225,7 +1283,8 @@ msgstr "Paramètre invalide" msgid "Invalid bits per value" msgstr "Bits par valeur invalides" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Longueur de tampon invalide" @@ -1254,14 +1313,10 @@ msgstr "Fichier invalide" msgid "Invalid format chunk size" msgstr "Taille de bloc de formatage invalide" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Fréquence non valide" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Fréquence invalide fournie" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Accès à la mémoire invalide." @@ -1300,17 +1355,13 @@ msgstr "Broche invalide pour le canal droit" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Broches invalides" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Broches invalides pour PWMOut" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1332,7 +1383,7 @@ msgstr "'security_mode' invalide" msgid "Invalid size" msgstr "Taille invalide" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "Socket non valide pour TLS" @@ -1340,10 +1391,6 @@ msgstr "Socket non valide pour TLS" msgid "Invalid state" msgstr "État invalide" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "Utilisation incorrecte de socket TLS" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "Voix invalide" @@ -1356,14 +1403,11 @@ msgstr "Nombre de voix invalide" msgid "Invalid wave file" msgstr "Fichier WAVE invalide" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Longueur de mot / bit invalide" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "Problème en activant SO_REUSEADDR" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "La clé doit comporter 16, 24 ou 32 octets" @@ -1409,14 +1453,6 @@ msgstr "La valeur maximale de x est %d lors d'une opération miroir" msgid "Messages limited to 8 bytes" msgstr "Messages limités à 8 octets" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "Échec du saut MicroPython NLR. Corruption de la mémoire probable." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Erreur fatale MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Le délais au démarrage du micro doit être entre 0.0 et 1.0" @@ -1428,32 +1464,34 @@ msgstr "Broche MISO ou MOSI manquante" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d reads pin(s)" -msgstr "" +msgstr "first_in_pin manquant. Instruction %d lit une/des broche(s)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d shifts in from pin(s)" msgstr "" +"first_in_pin manquant. Instruction %d est déplacée par la/les broche(s)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d waits based on pin" -msgstr "" +msgstr "first_in_pin manquant. L'instruction %d attends dépends de la broche" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d shifts out to pin(s)" msgstr "" +"first_out_pin manquant. Instruction %d est déplacée par la/les broche(s)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d writes pin(s)" -msgstr "" +msgstr "first_out_pin manquant. Instruction %d écrit un/des broche(s)" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_set_pin. Instruction %d sets pin(s)" -msgstr "" +msgstr "first_set_pin manquant. L'instruction %d règle la/les broche(s)" #: shared-bindings/displayio/Group.c msgid "Must be a %q subclass." @@ -1468,6 +1506,10 @@ msgstr "Doit fournir une broche MISO ou MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Doit utiliser un multiple de 6 broches RVB, pas %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "Saut NLR échoué. Corruption de mémoire probable." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "Erreur NVS" @@ -1487,9 +1529,15 @@ msgstr "Pas de DAC sur la puce" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Aucun canal DMA trouvé" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "Aucun minuteur de rythme DMA trouvé" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1548,6 +1596,14 @@ msgstr "Pas de support matériel sur la broche clk" msgid "No hardware support on pin" msgstr "Pas de support matériel pour cette broche" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "Programme n'a pas de \"in\"" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "Programme n'a aucun \"in\" ni \"out\"" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Aucune clé n'a été spécifiée" @@ -1556,25 +1612,19 @@ msgstr "Aucune clé n'a été spécifiée" msgid "No long integer support" msgstr "Pas de support pour chiffre entier long" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "Pas de canal supplémentaire disponible" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "Plus de minuteurs disponibles" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "Plus de minuteurs disponibles sur cette broche." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "Aucun réseau avec ce ssid" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No out in program" -msgstr "" +msgstr "Aucun out dans le programme" + +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "Aucun pull up trouvé sur SDA ou SCL; vérifiez votre cablage" #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" @@ -1593,13 +1643,18 @@ msgid "No timer available" msgstr "Aucun minuteur disponible" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Affirmation de défaillance du Nordic Soft Device." +msgid "Nordic system firmware failure assertion." +msgstr "Assertion échouée du logiciel systême Nordic." + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "Logiciel systême Nordic hors de mémoire" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "Chaîne IP non valide" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1630,13 +1685,10 @@ msgid "Odd parity is not supported" msgstr "Parité impaire non supportée" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Uniquement 8 ou 16 bit mono avec " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "Seulement les adresses IPv4 sont supportées" @@ -1690,10 +1742,19 @@ msgstr "Timeout de l'opération" msgid "Out of memory" msgstr "Hors de mémoire" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "Plus de sockets" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "Éléments du tampon de sortie doivent être <= à 4 octets" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "Tampon de sortie doit être au moins %d octets" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Le sur-échantillonage doit être un multiple de 8." @@ -1716,8 +1777,15 @@ msgstr "" "La fréquence de PWM n'est pas modifiable quand variable_frequency est False " "à la construction." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "PWM slice déja utilisée" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "Canal A de PWM slice est utilisé" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBus pas encore supporté" @@ -1732,11 +1800,11 @@ msgstr "Permission refusée" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Pin count must be at least 1" -msgstr "" +msgstr "Nombre de broches doit être au moins 1" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Pin count too large" -msgstr "" +msgstr "Nombre de broches trop élevé" #: ports/atmel-samd/common-hal/analogio/AnalogIn.c #: ports/cxd56/common-hal/analogio/AnalogIn.c @@ -1753,6 +1821,10 @@ msgstr "La broche 'pin' ne supporte pas les capacitées ADC" msgid "Pin is input only" msgstr "La broche est entrée uniquement" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "La broche doit être sur le canal B du PWM" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "La broche doit supporter les interruptions matérielles" @@ -1772,6 +1844,14 @@ msgstr "" "octets idéal. Si cela ne peut pas être évité, transmettez allow_inefficient " "= True au constructeur" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "Les broches doivent être séquentielles" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "Les broches doivent partager la tranche PWM" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Ainsi que tout autres modules présents sur le système de fichiers\n" @@ -1816,23 +1896,23 @@ msgstr "" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does IN without loading ISR" -msgstr "" +msgstr "Le programme fait des entrées sans charger d'ISR" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does OUT without loading OSR" -msgstr "" +msgstr "Le programme fait des sorties sans charger d'OSR" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program must contain at least one 16-bit instruction." -msgstr "" +msgstr "Le programme doit contenir au moins une instruction de 16 bits." #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program size invalid" -msgstr "" +msgstr "Taille du programme invalide" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program too large" -msgstr "" +msgstr "Programme trop grand" #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." @@ -1840,7 +1920,7 @@ msgstr "Le tirage 'pull' n'est pas utilisé quand la direction est 'output'." #: ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c msgid "RAISE mode is not implemented" -msgstr "" +msgstr "Mode RAISE n'est pas implémenté" #: ports/stm/common-hal/os/__init__.c msgid "RNG DeInit Error" @@ -1850,6 +1930,10 @@ msgstr "Erreur de désinitiation du RNG (RNG DeInit)" msgid "RNG Init Error" msgstr "Erreur d'initialisation du RNG (RNG Init)" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "RS485 n'est pas encore supporté sur cet appareil" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1857,6 +1941,7 @@ msgstr "Inversion RS485 spécifiée sans être en mode RS485" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "La calibration du RTC non supportée sur cette carte" @@ -1865,7 +1950,7 @@ msgid "RTC is not supported on this board" msgstr "RTC non supporté sur cette carte" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS / CTS / RS485 Pas encore supporté sur cet appareil" @@ -1922,12 +2007,6 @@ msgstr "Exécution en mode sécurisé! " msgid "SD card CSD format not supported" msgstr "Le format de carte SD CSD n'est pas supporté" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA ou SCL a besoin d'une résistance de tirage ('pull up')" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1948,7 +2027,7 @@ msgstr "Erreur de réinitialisation SPI" #: ports/raspberrypi/common-hal/busio/SPI.c msgid "SPI peripheral in use" -msgstr "" +msgstr "Périphérique SPI utilisé" #: shared-bindings/audiomixer/Mixer.c msgid "Sample rate must be positive" @@ -1963,14 +2042,6 @@ msgstr "Taux d'échantillonage trop élevé. Doit être inférieur à %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "Scan déjà en cours. Arrêtez avec stop_scan." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "La broche CTS sélectionnée n'est pas valide" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "La broche RTS sélectionnée n'est pas valide" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1982,11 +2053,11 @@ msgstr "Un contexte niveau serveur ne peut avoir de hostname" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Set pin count must be between 1 and 5" -msgstr "" +msgstr "Nombre de broches configurées doit être entre 1 et 5" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Side set pin count must be between 1 and 5" -msgstr "" +msgstr "Nombre de broches Side configurées doit être entre 1 et 5" #: ports/cxd56/common-hal/camera/Camera.c msgid "Size not supported" @@ -2019,6 +2090,14 @@ msgstr "Fractionnement avec des sous-captures" msgid "Stack size must be at least 256" msgstr "La pile doit être au moins de 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "Canal stéréo gauche doit être sur le canal PWM A" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "Canal stéréo droit doit être sur le canal PWM B" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Il manque une méthode readinto() ou write() au flux." @@ -2112,18 +2191,12 @@ msgstr "L'heure est dans le passé." msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "Le délai est trop long : le délai maximal est de %d secondes" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" -"Le minuteur est reservé pour un usage interne - déclarez la broche PWM plus " -"tôt dans le programme" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Pour quitter, SVP redémarrez la carte sans " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Trop de canaux dans l'échantillon." @@ -2136,9 +2209,8 @@ msgid "Too many displays" msgstr "Trop d'affichages" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "" -"Le nombre total de données à écrire est supérieur à outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "Quantité de données à écrire est plus que %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2164,10 +2236,6 @@ msgstr "Erreur d'initialisation UART" msgid "UART Re-init error" msgstr "Erreur de réinitialisation UART" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "Erreur d'écriture UART" @@ -2197,6 +2265,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Impossible d'allouer des tampons pour une conversion signée" @@ -2234,7 +2304,7 @@ msgstr "Écriture impossible vers sleep_memory." msgid "Unexpected nrfx uuid type" msgstr "Type inattendu pour l'uuid nrfx" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "Erreur ESP TLS non gérée %d %d %x %d" @@ -2260,8 +2330,8 @@ msgstr "Erreur de sécurité inconnue : 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Erreur de périphérique logiciel inconnue : %04x" +msgid "Unknown system firmware error: %04x" +msgstr "Faute inconnue du logiciel systême : %04x" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2291,7 +2361,7 @@ msgstr "Type de bus d'affichage non supporté" msgid "Unsupported format" msgstr "Format non supporté" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Opération non supportée" @@ -2317,11 +2387,6 @@ msgstr "Longueur de la valeur > max_length" msgid "Version was invalid" msgstr "Version est invalide" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" -"les fonctions de Viper ne supportent pas plus de 4 arguments actuellement" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "La lecture de la tension a expiré" @@ -2410,11 +2475,6 @@ msgstr "un objet 'bytes-like' est requis" msgid "abort() called" msgstr "abort() appelé" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "l'adresse %08x n'est pas alignée sur %d octets" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adresse hors limites" @@ -2423,26 +2483,26 @@ msgstr "adresse hors limites" msgid "addresses is empty" msgstr "adresses vides" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "l'argument est une séquence vide" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" -msgstr "L'argument argsort doit être un ndarray" +msgstr "Le paramêtre argsort doit être un ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" -msgstr "argsort n'est pas mis en œuvre pour les tableaux aplatis" +msgstr "argsort n'est pas mis en œuvre pour les matrices aplatis" #: py/runtime.c msgid "argument has wrong type" msgstr "l'argument est d'un mauvais type" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "l'argument doit être un ndarray" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2452,24 +2512,25 @@ msgstr "Nombre/types de paramètres ne correspondent pas" msgid "argument should be a '%q' not a '%q'" msgstr "le paramètre devrait être un(e) '%q', pas '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "les paramètres doivent être des ndarrays" #: extmod/ulab/code/ndarray.c msgid "array and index length must be equal" -msgstr "la longueur du tableau et de l'index doivent être égaux" +msgstr "la taille de la matrice et de l'index doivent être égaux" #: py/objarray.c shared-bindings/alarm/SleepMemory.c #: shared-bindings/nvm/ByteArray.c msgid "array/bytes required on right side" -msgstr "tableau/octets requis à droite" +msgstr "matrice/octets requis à la droite" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "tentative d’obtenir (arg)min/(arg)max d'une séquence vide" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "tenter d'obtenir argmin / argmax d'une séquence vide" @@ -2477,15 +2538,15 @@ msgstr "tenter d'obtenir argmin / argmax d'une séquence vide" msgid "attributes not supported yet" msgstr "attribut pas encore supporté" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "axis est hors limites" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "axis doit être None ou un entier" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "axis trop long" @@ -2510,8 +2571,8 @@ msgid "binary op %q not implemented" msgstr "opération binaire '%q' non implémentée" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bits doivent être 7, 8 ou 9" +msgid "bits must be in range 5 to 9" +msgstr "les bits doivent être compris entre 5 et 9" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2521,15 +2582,11 @@ msgstr "'bits_per_sample' doivent être 8 ou 16" msgid "branch not in range" msgstr "branche hors-bornes" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "tampon est plus petit que la taille demandée" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "le tampon doit être un objet bytes-like" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "taille du tampon doit être un multiple de la taille de l'élement" @@ -2546,7 +2603,7 @@ msgstr "les tranches de tampon doivent être de longueurs égales" msgid "buffer too small" msgstr "tampon trop petit" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "tampon trop petit pour le nombre d'octets demandé" @@ -2613,6 +2670,10 @@ msgstr "ne peut pas assigner à une expression" msgid "can't convert %q to %q" msgstr "impossible de convertir %q en %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "impossible de convertir l'objet '%q' en '%q' implicitement" @@ -2621,6 +2682,10 @@ msgstr "impossible de convertir l'objet '%q' en '%q' implicitement" msgid "can't convert to %q" msgstr "impossible de convertir en %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "ne peut convertir en entier 'int'" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "impossible de convertir en chaine 'str' implicitement" @@ -2747,6 +2812,10 @@ msgstr "paramètre de chr() hors les bornes de range(256)" msgid "circle can only be registered in one parent" msgstr "le cercle ne peut être enregistré que dans un seul parent" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "point de coupure doît être un tuple (x,y)" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "code hors bornes 0~127" @@ -2762,8 +2831,7 @@ msgstr "" #: shared-bindings/displayio/Palette.c msgid "color buffer must be a bytearray or array of type 'b' or 'B'" -msgstr "" -"le tampon de couleur doit être un bytearray ou un tableau de type 'b' ou 'B'" +msgstr "tampon color doit être un bytearray ou une matrice de type 'b' ou 'B'" #: shared-bindings/displayio/Palette.c msgid "color must be between 0x000000 and 0xffffff" @@ -2793,19 +2861,19 @@ msgstr "constante doit être un entier" msgid "conversion to object" msgstr "conversion en objet" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" -msgstr "les arguments convolve doivent être des tableaux linéaires" +msgstr "les paramêtres pour convolve doivent être des matrices linéaires" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" -msgstr "les arguments convolve doivent être des ndarrays" +msgstr "les paramêtres pour convolve doivent être des ndarrays" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "les arguments convolve ne doivent pas être vides" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "n'a pas pu inverser la matrice Vandermonde" @@ -2813,15 +2881,15 @@ msgstr "n'a pas pu inverser la matrice Vandermonde" msgid "couldn't determine SD card version" msgstr "impossible de déterminer la version de la carte SD" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" -msgstr "cross est défini pour les tableaux 1D de longueur 3" +msgstr "cross est défini pour les matrices 1D de longueur 3" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "les données doivent être les objets iterables" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "les données doivent être de longueur égale" @@ -2845,12 +2913,13 @@ msgstr "default n'est pas une fonction" msgid "" "destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -"le tampon de destination doit être un tableau de type 'B' pour bit_depth = 8" +"le tampon de destination doit être une matrice de type 'B' pour bit_depth = 8" #: shared-bindings/audiobusio/PDMIn.c msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -"le tampon de destination doit être un tableau de type 'H' pour bit_depth = 16" +"le tampon de destination doit être une matrice de type 'H' pour bit_depth = " +"16" #: shared-bindings/audiobusio/PDMIn.c msgid "destination_length must be an int >= 0" @@ -2860,14 +2929,18 @@ msgstr "destination_length doit être un entier >= 0" msgid "dict update sequence has wrong length" msgstr "la séquence de mise à jour de dict a une mauvaise longueur" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" -msgstr "l'argument diff doit être un ndarray" +msgstr "le paramêtre diff doit être un ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "differentiation order hors de portée" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "les dimensions ne correspondent pas" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2977,7 +3050,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string : single '}' n'est pas autorisé" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "le fichier doit être un fichier ouvert en mode 'byte'" @@ -2985,25 +3058,21 @@ msgstr "le fichier doit être un fichier ouvert en mode 'byte'" msgid "filesystem must provide mount method" msgstr "le system de fichier doit fournir une méthode 'mount'" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "le premier argument doit être un appelable" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "le premier argument doit être une fonction" #: extmod/ulab/code/ulab_create.c msgid "first argument must be a tuple of ndarrays" -msgstr "le premier argument doit être un tuple de ndarrays" - -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "le premier argument doit être un itérable" +msgstr "le premier paramêtre doit être un tuple de ndarrays" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" -msgstr "le premier argument doit être un ndarray" +msgstr "le premier paramêtre doit être un ndarray" #: py/objtype.c msgid "first argument to super() must be type" @@ -3013,9 +3082,9 @@ msgstr "le premier argument de super() doit être un type" msgid "flattening order must be either 'C', or 'F'" msgstr "l'ordre d'aplatissement doit être «C» ou «F»" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" -msgstr "l'argument flip doit être un ndarray" +msgstr "le paramêtre flip doit être un ndarray" #: py/objint.c msgid "float too big" @@ -3034,8 +3103,8 @@ msgid "full" msgstr "plein" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "la fonction ne prend pas d'arguments nommés" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3046,13 +3115,13 @@ msgstr "la fonction attendait au plus %d arguments, reçu %d" msgid "function got multiple values for argument '%q'" msgstr "la fonction a reçu plusieurs valeurs pour l'argument '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "la fonction a le même signe aux extrémités de l’intervalle" #: extmod/ulab/code/ndarray.c msgid "function is defined for ndarrays only" -msgstr "La fonction n'est définie que pour les ndarrays" +msgstr "fonction définie que pour les ndarrays" #: py/argcheck.c #, c-format @@ -3089,6 +3158,10 @@ msgstr "générateur déjà en cours d'exécution" msgid "generator ignored GeneratorExit" msgstr "le générateur a ignoré GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic doit être long de 2048 octets" @@ -3121,8 +3194,9 @@ msgstr "espacement incorrect" msgid "index is out of bounds" msgstr "l'index est hors limites" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "index est hors bornes" @@ -3135,7 +3209,7 @@ msgid "indices must be integers, slices, or Boolean lists" msgstr "" "les indices doivent être des entiers, des tranches ou des listes booléennes" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "les valeurs initiales doivent être itérables" @@ -3155,29 +3229,29 @@ msgstr "les formes d'entrée et de sortie ne sont pas compatibles" msgid "input argument must be an integer, a tuple, or a list" msgstr "Paramètre entrant doit être un chiffre entier, un tuple, ou une liste" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" -msgstr "la longueur du tableau d'entrée doit être une puissance de 2" +msgstr "longueur de la matrice d'entrée doit être une puissance de 2" #: extmod/ulab/code/ulab_create.c msgid "input arrays are not compatible" -msgstr "les tableaux d'entrée ne sont pas compatibles" +msgstr "les matrices d'entrée ne sont pas compatibles" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "les données d'entrée doivent être un itérable" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "la matrice d'entrée est asymétrique" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "la matrice d'entrée est singulière" #: extmod/ulab/code/user/user.c msgid "input must be a dense ndarray" -msgstr "l'entrée doit être un tableau dense" +msgstr "l'entrée doit être un ndarray dense" #: extmod/ulab/code/ulab_create.c msgid "input must be a tensor of rank 2" @@ -3187,23 +3261,23 @@ msgstr "l'entrée doit être un tenseur de rang 2" msgid "input must be an ndarray" msgstr "l'entrée doit être un ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "l'entrée doit être uni-dimensionelle" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "l'entrée doit être une matrice carrée" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "l'entrée 'input' doit être tuple, list, range ou ndarray" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "les vecteurs d'entrée doivent être de longueur égale" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "les entrées ne sont pas itérables" @@ -3215,9 +3289,9 @@ msgstr "l'argument 2 de int() doit être >=2 et <=36" msgid "integer required" msgstr "entier requis" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" -msgstr "interp est défini pour les tableaux 1D de longueur égale" +msgstr "interp est défini pour les matrices 1D de longueur égale" #: shared-bindings/_bleio/Adapter.c #, c-format @@ -3228,14 +3302,33 @@ msgstr "interval doit être dans la portée %s-%s" msgid "invalid arguments" msgstr "arguments invalides" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "bits_per_pixel %d est invalid, doit être 1, 4, 8, 16, 24 ou 32" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "certificat invalide" +#: py/compile.c +msgid "invalid decorator" +msgstr "décorateur invalide" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "index invalide pour dupterm" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "taille d'élément %d est invalide pour bits_per_pixel %d\n" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "element_size %d est invalide, doit être 1, 2 ou 4" + #: extmod/modframebuf.c msgid "invalid format" msgstr "format invalide" @@ -3277,10 +3370,6 @@ msgstr "syntaxe invalide pour un entier de base %d" msgid "invalid syntax for number" msgstr "syntaxe invalide pour un nombre" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io doit être rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "l'argument 1 de issubclass() doit être une classe" @@ -3290,11 +3379,7 @@ msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" "l'argument 2 de issubclass() doit être une classe ou un tuple de classes" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "les itérables ne sont pas de la même longueur" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "les itérations n'ont pas convergé" @@ -3365,11 +3450,7 @@ msgstr "tampon trop petit" msgid "math domain error" msgstr "erreur de domaine math" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "les dimensions de la matrice ne correspondent pas" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "la matrice n'est pas définie positive" @@ -3391,15 +3472,15 @@ msgstr "nombre maximal de dimensions est 4" msgid "maximum recursion depth exceeded" msgstr "profondeur maximale de récursivité dépassée" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "maxiter doit être > 0" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "maxiter devrait être > 0" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "Paramètre pour median doit être un ndarray" @@ -3412,11 +3493,15 @@ msgstr "l'allocation de mémoire a échoué en allouant %u octets" msgid "memory allocation failed, heap is locked" msgstr "l'allocation de mémoire a échoué, le tas est vérrouillé" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "memoryview: length n'est pas un multiple de itemsize" + #: py/builtinimport.c msgid "module not found" msgstr "module introuvable" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "plus de degrés de liberté que de points de données" @@ -3461,6 +3546,10 @@ msgstr "'yield' natif" msgid "need more than %d values to unpack" msgstr "nécessite plus de %d valeurs à dégrouper" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "puissance négative sans support des nombres à virgule flottante" @@ -3535,10 +3624,6 @@ msgstr "le délai non-zéro doit être > 0.01" msgid "non-zero timeout must be >= interval" msgstr "le délai non-zéro doit être >= interval" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "norm est défini pour des tableaux 1D et 2D" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "n'est pas un UUID 128 bits" @@ -3608,7 +3693,7 @@ msgstr "un objet avec un protocole de tampon est nécessaire" msgid "odd-length string" msgstr "chaîne de longueur impaire" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "offset est trop large" @@ -3637,18 +3722,18 @@ msgstr "seul sample_rate = 16000 est pris en charge" msgid "only slices with step=1 (aka None) are supported" msgstr "seules les tranches avec 'step=1' (cad None) sont supportées" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "les opérandes ne pouvaient pas être diffusés ensemble" #: extmod/ulab/code/ndarray.c msgid "operation is implemented for 1D Boolean arrays only" -msgstr "opération implémentée que pour des tableaux 1D booléennes" +msgstr "opération implémentée que pour les matrices 1D booléennes" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" -msgstr "l'opération n'est pas implémentée sur les ndarrays" +msgstr "l'opération n'est pas implémentée pour les ndarrays" #: extmod/ulab/code/ndarray.c msgid "operation is not supported for given type" @@ -3665,11 +3750,19 @@ msgstr "" "ord() attend un caractère mais une chaîne de caractère de longueur %d a été " "trouvée" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "matrice de sortie est trop petite" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "la matrice sortante doit être de type float" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "dépassement des bornes de source" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "dépassement des bornes de target" @@ -3690,10 +3783,6 @@ msgstr "la palette doit être longue de 32 octets" msgid "palette_index should be an int" msgstr "palette_index devrait être un entier 'int'" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "l'annotation du paramètre doit être un identifiant" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "les paramètres doivent être des registres dans la séquence a2 à a5" @@ -3702,7 +3791,7 @@ msgstr "les paramètres doivent être des registres dans la séquence a2 à a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "les paramètres doivent être des registres dans la séquence r0 à r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "coordonnées de pixel hors limites" @@ -3726,11 +3815,16 @@ msgstr "'pop' d'une entrée PulseIn vide" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "pop sur %q vide" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "port doit être >= 0" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "le 3e argument de pow() ne peut être 0" @@ -3741,12 +3835,17 @@ msgstr "pow() avec 3 arguments nécessite des entiers" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3754,6 +3853,7 @@ msgstr "pow() avec 3 arguments nécessite des entiers" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "bouton boot appuyé lors du démarrage.\n" @@ -3765,13 +3865,21 @@ msgstr "bouton boot appuyé lors du démarrage.\n" msgid "pressing both buttons at start up.\n" msgstr "les deux boutons appuyés lors du démarrage.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "appuyer le bouton de gauche au démarage\n" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "masque pull est en conflit avec les masques de direction" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" -msgstr "" +msgstr "pull_threshold doit être entre 1 et 32" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "push_threshold must be between 1 and 32" -msgstr "" +msgstr "push_threshold doit être entre 1 et 32" #: extmod/modutimeq.c msgid "queue overflow" @@ -3781,7 +3889,7 @@ msgstr "dépassement de file" msgid "raw f-strings are not implemented" msgstr "les chaînes f brutes ne sont pas implémentées" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "les parties réelles et imaginaires doivent être de longueur égale" @@ -3816,7 +3924,7 @@ msgstr "rgb_pins[%d] duplique une autre affectation de broches" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins[%d] n'est pas sur le même port que l'horloge" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "paramêtre roll doit être un ndarray" @@ -3829,10 +3937,11 @@ msgid "" "sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or " "'B'" msgstr "" -"le tampon de sample_source doit être un bytearray ou un tableau de type " -"'h','H', 'b' ou 'B'" +"tampon sample_source doit être un bytearray ou une matrice de type 'h', 'H', " +"'b' ou 'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "taux d'échantillonage hors bornes" @@ -3864,9 +3973,9 @@ msgstr "signe non autorisé avec la spéc. de format d'entier 'c'" msgid "single '}' encountered in format string" msgstr "'}' seule rencontrée dans une chaîne de format" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" -msgstr "la taille est définie pour les ndarrays uniquement" +msgstr "la taille n'est définie que pour les ndarrays" #: shared-bindings/time/__init__.c msgid "sleep length must be non-negative" @@ -3888,23 +3997,23 @@ msgstr "dépassement de capacité d'un entier court" msgid "soft reboot\n" msgstr "redémarrage logiciel\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" -msgstr "l'argument de «sort» doit être un ndarray" +msgstr "le paramètre de «sort» doit être un ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" -msgstr "le tableau sos doit être de forme (n_section, 6)" +msgstr "la matrice sos doit être de forme (n_section, 6)" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "sos[:, 3] doivent tous être à un" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "sosfilt nécessite des argument itératifs" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "la palette source est trop grande" @@ -3939,7 +4048,7 @@ msgstr "les indices d'une chaîne doivent être des entiers, pas %q" #: py/stream.c msgid "string not supported; use bytes or bytearray" msgstr "" -"chaîne de carac. non supportée ; utilisez des bytes ou un tableau de bytes" +"chaîne de carac. non supportée; utilisez des bytes ou une matrice de bytes" #: extmod/moductypes.c msgid "struct: cannot index" @@ -4009,13 +4118,13 @@ msgstr "timestamp hors bornes pour 'time_t' de la plateforme" #: extmod/ulab/code/ndarray.c msgid "tobytes can be invoked for dense arrays only" -msgstr "tobytes ne peut être appelé que pour des tableaux dense" +msgstr "tobytes ne peut être appelée que pour des matrices dense" #: shared-module/struct/__init__.c msgid "too many arguments provided with the given format" msgstr "trop d'arguments fournis avec ce format" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "Trop de dimensions" @@ -4028,17 +4137,13 @@ msgstr "trop d'indices" msgid "too many values to unpack (expected %d)" msgstr "trop de valeur à dégrouper (%d attendues)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" -msgstr "trapz est défini pour tableaux à une dimension" +msgstr "trapz est définie pour matrices à une dimension" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" -msgstr "trapz n'est défini que pour des tableaux 1D de longueur égale" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "niveau du déclencheur doit être 0 ou 1" +msgstr "trapz n'est défini que pour des matrices 1D de longueur égales" #: py/obj.c msgid "tuple/list has wrong length" @@ -4121,7 +4226,7 @@ msgstr "code de formatage inconnu '%c' pour objet de type '%q'" msgid "unknown type" msgstr "type inconnu" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "type '%q' inconnu" @@ -4174,14 +4279,6 @@ msgstr "la valeur doit tenir dans %d octet(s)" msgid "value_count must be > 0" msgstr "'value_count' doit être > 0" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "les vecteurs doivent avoir la même longueur" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "conflit au réveil" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "chien de garde (watchdog) non initialisé" @@ -4190,6 +4287,11 @@ msgstr "chien de garde (watchdog) non initialisé" msgid "watchdog timeout must be greater than 0" msgstr "watchdog timeout doit être supérieur à 0" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "width doit être entre 2 et 8 (inclusivement), non %d" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "width doit être plus que zero" @@ -4202,7 +4304,7 @@ msgstr "wifi n’est pas activé" msgid "window must be <= interval" msgstr "la fenêtre (window) doit être <= intervalle (interval)" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "index d'axe incorrecte" @@ -4210,7 +4312,8 @@ msgstr "index d'axe incorrecte" msgid "wrong axis specified" msgstr "axe incorrecte spécifiée" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "type d'entrée incorrect" @@ -4226,7 +4329,7 @@ msgstr "mauvais nombre de valeurs à dégrouper" msgid "wrong operand type" msgstr "type d'opérande incorrect" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "type de sortie incorrect" @@ -4250,18 +4353,143 @@ msgstr "valeur y hors limites" msgid "zero step" msgstr "'step' nul" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" -msgstr "zi doit être ndarray" +msgstr "zi doit être un ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "zi doit être de type float" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "zi doit être de forme (n_section, 2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "" +#~ "les fonctions de Viper ne supportent pas plus de 4 arguments actuellement" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "l'adresse %08x n'est pas alignée sur %d octets" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "la fonction ne prend pas d'arguments nommés" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "l'annotation du paramètre doit être un identifiant" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "Le nombre total de données à écrire est supérieur à outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 & 4 ne supportent pas l'éleveuse interne en mode someil" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "le tampon doit être un objet bytes-like" + +#~ msgid "io must be rtc io" +#~ msgstr "io doit être rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "niveau du déclencheur doit être 0 ou 1" + +#~ msgid "wakeup conflict" +#~ msgstr "conflit au réveil" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "Tentative d'allocation de segments lorsque la machine virtuelle " +#~ "MicroPython n'est pas en cours d'exécution." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "Échec du saut MicroPython NLR. Corruption de la mémoire probable." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Erreur fatale MicroPython." + +#~ msgid "argument must be ndarray" +#~ msgstr "l'argument doit être un ndarray" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "les dimensions de la matrice ne correspondent pas" + +#~ msgid "norm is defined for 1D and 2D arrays" +#~ msgstr "norm est défini pour des tableaux 1D et 2D" + +#~ msgid "vectors must have same lengths" +#~ msgstr "les vecteurs doivent avoir la même longueur" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Affirmation de défaillance du Nordic Soft Device." + +#~ msgid "Nordic soft device out of memory" +#~ msgstr "Appareil logiciel Nordic hors de mémoire" + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Erreur de périphérique logiciel inconnue : %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "le premier argument doit être un itérable" + +#~ msgid "iterables are not of the same length" +#~ msgstr "les itérables ne sont pas de la même longueur" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "La broche CTS sélectionnée n'est pas valide" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "La broche RTS sélectionnée n'est pas valide" + +#~ msgid "Could not initialize channel" +#~ msgstr "Impossible d'initialiser le canal" + +#~ msgid "Could not initialize timer" +#~ msgstr "Impossible d'initialiser le minuteur" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Fréquence invalide fournie" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Broches invalides pour PWMOut" + +#~ msgid "No more channels available" +#~ msgstr "Pas de canal supplémentaire disponible" + +#~ msgid "No more timers available" +#~ msgstr "Plus de minuteurs disponibles" + +#~ msgid "No more timers available on this pin." +#~ msgstr "Plus de minuteurs disponibles sur cette broche." + +#~ msgid "" +#~ "Timer was reserved for internal use - declare PWM pins earlier in the " +#~ "program" +#~ msgstr "" +#~ "Le minuteur est reservé pour un usage interne - déclarez la broche PWM " +#~ "plus tôt dans le programme" + +#~ msgid "Group full" +#~ msgstr "Groupe plein" + +#~ msgid "UART not yet supported" +#~ msgstr "UART n'est pas encore supporté" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bits doivent être 7, 8 ou 9" + +#~ msgid "Only IN/OUT of up to 8 supported" +#~ msgstr "Seulement des IN/OUT jusqu'à 8 est supporté" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA ou SCL a besoin d'une résistance de tirage ('pull up')" + +#~ msgid "Invalid use of TLS Socket" +#~ msgstr "Utilisation incorrecte de socket TLS" + +#~ msgid "Issue setting SO_REUSEADDR" +#~ msgstr "Problème en activant SO_REUSEADDR" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "" #~ "Les broches d'adresse %d et les broches RVB %d indiquent une hauteur de " @@ -4447,9 +4675,6 @@ msgstr "zi doit être de forme (n_section, 2)" #~ msgid "can't convert to float" #~ msgstr "ne peut convertir en nombre à virgule flottante 'float'" -#~ msgid "can't convert to int" -#~ msgstr "ne peut convertir en entier 'int'" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "l'objet '%s' n'est pas un tuple ou une liste" diff --git a/locale/hi.po b/locale/hi.po index 5150d164e1c0b..ff2a0530e530c 100644 --- a/locale/hi.po +++ b/locale/hi.po @@ -73,6 +73,7 @@ msgstr "" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -102,6 +103,7 @@ msgstr "" msgid "%q must be a tuple of length 2" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "" @@ -332,9 +334,14 @@ msgid "All SPI peripherals are in use" msgstr "" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "" @@ -363,6 +370,7 @@ msgstr "" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "" @@ -403,6 +411,10 @@ msgstr "" msgid "AnalogOut not supported on given pin" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -426,7 +438,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -452,6 +464,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "" @@ -493,6 +509,10 @@ msgstr "" msgid "Buffer + offset too small %d %d %d" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -509,6 +529,7 @@ msgid "Buffer is too small" msgstr "" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "" @@ -538,6 +559,7 @@ msgstr "" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "" @@ -629,6 +651,10 @@ msgstr "" msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "" @@ -650,7 +676,7 @@ msgstr "" msgid "Cannot unambiguously get sizeof scalar" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" @@ -732,14 +758,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "" @@ -760,7 +778,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "" @@ -861,11 +879,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -916,15 +939,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -938,6 +961,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "" @@ -946,6 +970,7 @@ msgstr "" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -959,6 +984,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "" @@ -984,6 +1013,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1007,7 +1040,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1026,10 +1059,6 @@ msgstr "" msgid "Group already used" msgstr "" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1060,15 +1089,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1083,10 +1112,23 @@ msgstr "" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1143,6 +1185,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "" @@ -1169,8 +1212,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "" @@ -1188,7 +1237,8 @@ msgstr "" msgid "Invalid bits per value" msgstr "" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "" @@ -1217,14 +1267,10 @@ msgstr "" msgid "Invalid format chunk size" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "" @@ -1263,17 +1309,13 @@ msgstr "" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1295,7 +1337,7 @@ msgstr "" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1303,10 +1345,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1319,14 +1357,11 @@ msgstr "" msgid "Invalid wave file" msgstr "" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "" @@ -1372,14 +1407,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1431,6 +1458,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1450,9 +1481,15 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1511,24 +1548,20 @@ msgstr "" msgid "No hardware support on pin" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "No key was specified" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" +#: shared-bindings/aesio/aes.c +msgid "No key was specified" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." +#: shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" #: shared-bindings/wifi/Radio.c @@ -1539,6 +1572,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1556,13 +1595,18 @@ msgid "No timer available" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1591,13 +1635,10 @@ msgid "Odd parity is not supported" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1647,10 +1688,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "" @@ -1669,8 +1719,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "" @@ -1706,6 +1763,10 @@ msgstr "" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "" @@ -1722,6 +1783,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "" @@ -1793,6 +1862,10 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1800,6 +1873,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "" @@ -1808,7 +1882,7 @@ msgid "RTC is not supported on this board" msgstr "" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "" @@ -1865,12 +1939,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1906,14 +1974,6 @@ msgstr "" msgid "Scan already in progess. Stop with stop_scan." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1962,6 +2022,14 @@ msgstr "" msgid "Stack size must be at least 256" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "" @@ -2046,16 +2114,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "" @@ -2068,7 +2132,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2095,10 +2159,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "" @@ -2125,6 +2185,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "" @@ -2162,7 +2224,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2188,7 +2250,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2216,7 +2278,7 @@ msgstr "" msgid "Unsupported format" msgstr "" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "" @@ -2242,10 +2304,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2325,11 +2383,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2338,15 +2391,19 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2354,10 +2411,6 @@ msgstr "" msgid "argument has wrong type" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2367,7 +2420,8 @@ msgstr "" msgid "argument should be a '%q' not a '%q'" msgstr "" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2380,11 +2434,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2392,15 +2446,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2425,7 +2479,7 @@ msgid "binary op %q not implemented" msgstr "" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" +msgid "bits must be in range 5 to 9" msgstr "" #: shared-bindings/audiomixer/Mixer.c @@ -2436,15 +2490,11 @@ msgstr "" msgid "branch not in range" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2461,7 +2511,7 @@ msgstr "" msgid "buffer too small" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2527,6 +2577,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2535,6 +2589,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2653,6 +2711,10 @@ msgstr "" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2697,19 +2759,19 @@ msgstr "" msgid "conversion to object" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2717,15 +2779,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2762,14 +2824,18 @@ msgstr "" msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2877,7 +2943,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2885,11 +2951,11 @@ msgstr "" msgid "filesystem must provide mount method" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2897,11 +2963,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2913,7 +2975,7 @@ msgstr "" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2934,7 +2996,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -2946,7 +3008,7 @@ msgstr "" msgid "function got multiple values for argument '%q'" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -2989,6 +3051,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3021,8 +3087,9 @@ msgstr "" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "" @@ -3034,7 +3101,7 @@ msgstr "" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3054,7 +3121,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3062,15 +3129,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3086,23 +3153,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3114,7 +3181,7 @@ msgstr "" msgid "integer required" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3127,14 +3194,33 @@ msgstr "" msgid "invalid arguments" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "" @@ -3176,10 +3262,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3188,11 +3270,7 @@ msgstr "" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3260,11 +3338,7 @@ msgstr "" msgid "math domain error" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3286,15 +3360,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3307,11 +3381,15 @@ msgstr "" msgid "memory allocation failed, heap is locked" msgstr "" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3356,6 +3434,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3429,10 +3511,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3501,7 +3579,7 @@ msgstr "" msgid "odd-length string" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3530,8 +3608,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3539,7 +3617,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3556,11 +3634,19 @@ msgstr "" msgid "ord() expected a character, but string of length %d found" msgstr "" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3581,10 +3667,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3593,7 +3675,7 @@ msgstr "" msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "" @@ -3616,11 +3698,16 @@ msgstr "" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "" @@ -3631,12 +3718,17 @@ msgstr "" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3644,6 +3736,7 @@ msgstr "" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3655,6 +3748,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3671,7 +3772,7 @@ msgstr "" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3706,7 +3807,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3721,6 +3822,7 @@ msgid "" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "" @@ -3752,7 +3854,7 @@ msgstr "" msgid "single '}' encountered in format string" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3776,23 +3878,23 @@ msgstr "" msgid "soft reboot\n" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3902,7 +4004,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3915,18 +4017,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4008,7 +4106,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4061,14 +4159,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4077,6 +4167,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4089,7 +4184,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4097,7 +4192,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4113,7 +4209,7 @@ msgstr "" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4137,14 +4233,14 @@ msgstr "" msgid "zero step" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" diff --git a/locale/it_IT.po b/locale/it_IT.po index cecfe112987a1..188e25d16f080 100644 --- a/locale/it_IT.po +++ b/locale/it_IT.po @@ -7,25 +7,31 @@ msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2018-10-02 16:27+0200\n" -"Last-Translator: Enrico Paganin \n" +"PO-Revision-Date: 2021-03-16 14:54+0000\n" +"Last-Translator: Alessandro Mandelli \n" "Language-Team: \n" "Language: it_IT\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=n != 1;\n" +"X-Generator: Weblate 4.5.2-dev\n" #: main.c msgid "" "\n" "Code done running.\n" msgstr "" +"\n" +"Caricamento codice pronto.\n" #: main.c msgid "" "\n" "Code stopped by auto-reload.\n" msgstr "" +"\n" +"Codice fermato dall'auto-ricarica.\n" #: supervisor/shared/safe_mode.c msgid "" @@ -33,6 +39,9 @@ msgid "" "Please file an issue with the contents of your CIRCUITPY drive at \n" "https://github.com/adafruit/circuitpython/issues\n" msgstr "" +"\n" +"Per favore, segnala il problema con il contenuto del tuo CIRCUITPY a\n" +"https://github.com/adafruit/circuitpython/issues\n" #: py/obj.c msgid " File \"%q\"" @@ -44,7 +53,7 @@ msgstr " File \"%q\", riga %d" #: py/builtinhelp.c msgid " is of type %q\n" -msgstr "" +msgstr " è di tipo %q\n" #: main.c msgid " output:\n" @@ -60,10 +69,11 @@ msgstr "%%c necessita di int o char" msgid "" "%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" msgstr "" +"%d pin indirizzo, %d pin rgb e %d tessere indicano l'altezza di %d, non %d" #: ports/atmel-samd/common-hal/sdioio/SDCard.c msgid "%q failure: %d" -msgstr "" +msgstr "%q fallito: %d" #: shared-bindings/microcontroller/Pin.c msgid "%q in use" @@ -72,6 +82,7 @@ msgstr "%q in uso" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -79,15 +90,15 @@ msgstr "indice %q fuori intervallo" #: py/obj.c msgid "%q indices must be integers, not %q" -msgstr "" +msgstr "%q gli indici devono essere interi, non %q" #: shared-bindings/vectorio/Polygon.c msgid "%q list must be a list" -msgstr "" +msgstr "lista %q deve essere una lista" #: shared-bindings/memorymonitor/AllocationAlarm.c msgid "%q must be >= 0" -msgstr "" +msgstr "%q deve essere >= 0" #: shared-bindings/_bleio/CharacteristicBuffer.c #: shared-bindings/_bleio/PacketBuffer.c shared-bindings/displayio/Group.c @@ -100,20 +111,20 @@ msgstr "slice del buffer devono essere della stessa lunghezza" #: shared-module/vectorio/Polygon.c msgid "%q must be a tuple of length 2" -msgstr "" +msgstr "%q deve essere una tupla di lunghezza 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" -msgstr "" +msgstr "%q oltre il limite" #: ports/atmel-samd/common-hal/microcontroller/Pin.c msgid "%q pin invalid" -msgstr "" +msgstr "%q pin non valido" #: shared-bindings/fontio/BuiltinFont.c -#, fuzzy msgid "%q should be an int" -msgstr "y dovrebbe essere un int" +msgstr "%q dovrebbe essere un int" #: py/bc.c py/objnamedtuple.c msgid "%q() takes %d positional arguments but %d were given" @@ -122,7 +133,7 @@ msgstr "%q() prende %d argomenti posizionali ma ne sono stati forniti %d" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c #, c-format msgid "%s error 0x%x" -msgstr "" +msgstr "%s errore 0x%x" #: py/argcheck.c msgid "'%q' argument required" @@ -130,93 +141,93 @@ msgstr "'%q' argomento richiesto" #: py/runtime.c msgid "'%q' object cannot assign attribute '%q'" -msgstr "" +msgstr "L'oggetto '%q' non può assegnare l'attributo '%q'" #: py/proto.c msgid "'%q' object does not support '%q'" -msgstr "" +msgstr "L'oggetto '%q' non supporta '%q'" #: py/obj.c msgid "'%q' object does not support item assignment" -msgstr "" +msgstr "L'oggetto '%q' non supporta l'assegnazione dell'elemento" #: py/obj.c msgid "'%q' object does not support item deletion" -msgstr "" +msgstr "L'oggetto '%q' non supporta la rimozione dell'elemento" #: py/runtime.c msgid "'%q' object has no attribute '%q'" -msgstr "" +msgstr "L'oggetto '%q' non ha attributi '%q'" #: py/runtime.c msgid "'%q' object is not an iterator" -msgstr "" +msgstr "L'oggetto '%q' non è un iteratore" #: py/objtype.c py/runtime.c msgid "'%q' object is not callable" -msgstr "" +msgstr "L'oggetto '%q' non è richiamabile" #: py/runtime.c msgid "'%q' object is not iterable" -msgstr "" +msgstr "L'oggetto '%q' non è iterabile" #: py/obj.c msgid "'%q' object is not subscriptable" -msgstr "" +msgstr "l'oggetto '%q' non è riscrivibile" #: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format msgid "'%s' expects a label" -msgstr "'%s' aspetta una etichetta" +msgstr "'%s' richiede una etichetta" #: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format msgid "'%s' expects a register" -msgstr "'%s' aspetta un registro" +msgstr "'%s' richiede un registro" #: py/emitinlinethumb.c -#, fuzzy, c-format +#, c-format msgid "'%s' expects a special register" -msgstr "'%s' aspetta un registro" +msgstr "'%s' richiede un registro speciale" #: py/emitinlinethumb.c -#, fuzzy, c-format +#, c-format msgid "'%s' expects an FPU register" -msgstr "'%s' aspetta un registro" +msgstr "'%s' richiede un registro FPU" #: py/emitinlinethumb.c -#, fuzzy, c-format +#, c-format msgid "'%s' expects an address of the form [a, b]" -msgstr "'%s' aspetta un registro" +msgstr "'%s' richiede un indirizzo dal modulo [a, b]" #: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format msgid "'%s' expects an integer" -msgstr "'%s' aspetta un intero" +msgstr "'%s' richiede un valore intero" #: py/emitinlinethumb.c -#, fuzzy, c-format +#, c-format msgid "'%s' expects at most r%d" -msgstr "'%s' aspetta un registro" +msgstr "'%s' richiede almeno r%d" #: py/emitinlinethumb.c -#, fuzzy, c-format +#, c-format msgid "'%s' expects {r0, r1, ...}" -msgstr "'%s' aspetta un registro" +msgstr "'%s' richiede {r0, r1, ...}" #: py/emitinlinextensa.c -#, fuzzy, c-format +#, c-format msgid "'%s' integer %d is not within range %d..%d" -msgstr "intero '%s' non è nell'intervallo %d..%d" +msgstr "Valore intero '%s' %d non è nell'intervallo %d..%d" #: py/emitinlinethumb.c -#, fuzzy, c-format +#, c-format msgid "'%s' integer 0x%x does not fit in mask 0x%x" -msgstr "intero '%s' non è nell'intervallo %d..%d" +msgstr "Valore intero '%s' 0x%x non rientra nella maschera 0x%x" #: py/objstr.c msgid "'=' alignment not allowed in string format specifier" -msgstr "aligniamento '=' non è permesso per il specificatore formato string" +msgstr "Allineamento'=' non è permesso per lo specificatore formato stringa" #: shared-module/struct/__init__.c msgid "'S' and 'O' are not supported format types" @@ -233,22 +244,23 @@ msgstr "'await' al di fuori della funzione" #: py/compile.c msgid "'await', 'async for' or 'async with' outside async function" msgstr "" +"'await', 'async for' o 'async with' fuori della funzione sincronizzazione" #: py/compile.c msgid "'break' outside loop" -msgstr "'break' al di fuori del ciclo" +msgstr "'break' fuori del ciclo" #: py/compile.c msgid "'continue' outside loop" -msgstr "'continue' al di fuori del ciclo" +msgstr "'continue' fuori del ciclo" #: py/objgenerator.c msgid "'coroutine' object is not an iterator" -msgstr "" +msgstr "L'oggetto 'coroutine' non è un iteratore" #: py/compile.c msgid "'data' requires at least 2 arguments" -msgstr "'data' richiede almeno 2 argomento" +msgstr "'data' richiede almeno 2 argomenti" #: py/compile.c msgid "'data' requires integer arguments" @@ -264,7 +276,7 @@ msgstr "'return' al di fuori della funzione" #: py/compile.c msgid "'yield from' inside async function" -msgstr "" +msgstr "'yield from' è nella funzione sincronizzazione" #: py/compile.c msgid "'yield' outside function" @@ -288,29 +300,29 @@ msgstr "pow() con tre argmomenti non supportata" #: shared-module/msgpack/__init__.c msgid "64 bit types" -msgstr "" +msgstr "Tipo 64 bits" #: ports/atmel-samd/common-hal/countio/Counter.c #: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c msgid "A hardware interrupt channel is already in use" -msgstr "Un canale di interrupt hardware è già in uso" +msgstr "Un canale di interruzione hardware è già in uso" #: ports/esp32s2/common-hal/analogio/AnalogIn.c msgid "ADC2 is being used by WiFi" -msgstr "" +msgstr "ADC2 sta usando il WiFi" #: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, fuzzy, c-format +#, c-format msgid "Address must be %d bytes long" -msgstr "la palette deve essere lunga 32 byte" +msgstr "L'indirizzo deve essere lungo %d byte" #: shared-bindings/_bleio/Address.c msgid "Address type out of range" -msgstr "" +msgstr "Tipo di indirizzo fuori intervallo" #: ports/esp32s2/common-hal/canio/CAN.c msgid "All CAN peripherals are in use" -msgstr "" +msgstr "Tutte le periferiche CAN sono in uso" #: ports/esp32s2/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c msgid "All I2C peripherals are in use" @@ -320,30 +332,35 @@ msgstr "Tutte le periferiche I2C sono in uso" #: ports/esp32s2/common-hal/frequencyio/FrequencyIn.c #: ports/esp32s2/common-hal/rotaryio/IncrementalEncoder.c msgid "All PCNT units in use" -msgstr "" +msgstr "Tutte le unità PCNT sono in uso" #: ports/atmel-samd/common-hal/canio/Listener.c #: ports/esp32s2/common-hal/canio/Listener.c #: ports/stm/common-hal/canio/Listener.c msgid "All RX FIFOs in use" -msgstr "" +msgstr "Tutte le RX FIFO sono in uso" #: ports/esp32s2/common-hal/busio/SPI.c ports/nrf/common-hal/busio/SPI.c msgid "All SPI peripherals are in use" msgstr "Tutte le periferiche SPI sono in uso" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c #, fuzzy msgid "All UART peripherals are in use" msgstr "Tutte le periferiche I2C sono in uso" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Tutti i canali eventi utilizati" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "All state machines in use" -msgstr "" +msgstr "Tutte le state machines sono in uso" #: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "All sync event channels in use" @@ -365,6 +382,7 @@ msgstr "Tutti i timer per questo pin sono in uso" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Tutti i timer utilizzati" @@ -375,16 +393,16 @@ msgstr "" #: ports/atmel-samd/common-hal/canio/Listener.c msgid "Already have all-matches listener" -msgstr "" +msgstr "Già in possesso di tutti i listener abbinati" #: shared-module/memorymonitor/AllocationAlarm.c #: shared-module/memorymonitor/AllocationSize.c msgid "Already running" -msgstr "" +msgstr "Già in funzione" #: ports/esp32s2/common-hal/wifi/Radio.c msgid "Already scanning for wifi networks" -msgstr "" +msgstr "Già in ricerca di collegamenti WiFi" #: ports/cxd56/common-hal/analogio/AnalogIn.c msgid "AnalogIn not supported on given pin" @@ -405,6 +423,10 @@ msgstr "AnalogOut ha solo 16 bit. Il valore deve essere meno di 65536." msgid "AnalogOut not supported on given pin" msgstr "AnalogOut non supportato sul pin scelto" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -416,24 +438,24 @@ msgstr "Array deve avere mezzoparole (typo 'H')" #: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c msgid "Array values should be single bytes." -msgstr "Valori di Array dovrebbero essere bytes singulari" +msgstr "I valori dell'Array dovrebbero essere bytes singoli." #: shared-bindings/microcontroller/Pin.c msgid "At most %d %q may be specified (not %d)" -msgstr "" +msgstr "Almeno %d %q devono essere specificati (non %d)" #: shared-module/memorymonitor/AllocationAlarm.c #, c-format msgid "Attempt to allocate %d blocks" -msgstr "" +msgstr "Provo ad allocare %d blocchi" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" -msgstr "" +msgstr "Autenticazione Fallita" #: main.c msgid "Auto-reload is off.\n" @@ -454,6 +476,10 @@ msgstr "" #: shared-module/displayio/Display.c #: shared-module/framebufferio/FramebufferDisplay.c msgid "Below minimum frame rate" +msgstr "Al di sotto del frame rate minimo" + +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c @@ -464,15 +490,15 @@ msgstr "" #: shared-bindings/rgbmatrix/RGBMatrix.c #, c-format msgid "Bit depth must be from 1 to 6 inclusive, not %d" -msgstr "" +msgstr "La profondità dei bit deve essere inclusiva da 1 a 6, non %d" #: shared-bindings/audiobusio/PDMIn.c msgid "Bit depth must be multiple of 8." -msgstr "La profondità di bit deve essere multipla di 8." +msgstr "La profondità di bit deve essere un multiplo di 8." #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Both RX and TX required for flow control" -msgstr "" +msgstr "Sia RX che TX richiedono il controllo del flow" #: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c msgid "Both pins must support hardware interrupts" @@ -482,20 +508,24 @@ msgstr "Entrambi i pin devono supportare gli interrupt hardware" #: shared-bindings/framebufferio/FramebufferDisplay.c #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "Brightness must be 0-1.0" -msgstr "" +msgstr "La luminosità deve essere tra 0-1.0" #: shared-bindings/supervisor/__init__.c msgid "Brightness must be between 0 and 255" -msgstr "La luminosità deve essere compreso tra 0 e 255" +msgstr "La luminosità deve essere compresa tra 0 e 255" #: shared-bindings/displayio/Display.c #: shared-bindings/framebufferio/FramebufferDisplay.c msgid "Brightness not adjustable" -msgstr "Illiminazione non è regolabile" +msgstr "Luminosità non è regolabile" #: shared-bindings/_bleio/UUID.c #, c-format msgid "Buffer + offset too small %d %d %d" +msgstr "Buffer + offset troppo piccolo %d %d %d" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" msgstr "" #: shared-module/usb_hid/Device.c @@ -506,26 +536,27 @@ msgstr "Buffer di lunghezza non valida. Dovrebbe essere di %d bytes." #: shared-bindings/displayio/Display.c #: shared-bindings/framebufferio/FramebufferDisplay.c msgid "Buffer is not a bytearray." -msgstr "" +msgstr "Buffer non è un array di bites." #: ports/cxd56/common-hal/camera/Camera.c shared-bindings/displayio/Display.c #: shared-bindings/framebufferio/FramebufferDisplay.c msgid "Buffer is too small" -msgstr "" +msgstr "Buffer troppo piccolo" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" -msgstr "" +msgstr "Lunghezza Buffer %d troppo grande. Deve essere meno di %d" #: ports/atmel-samd/common-hal/sdioio/SDCard.c #: ports/cxd56/common-hal/sdioio/SDCard.c shared-module/sdcardio/SDCard.c msgid "Buffer length must be a multiple of 512" -msgstr "" +msgstr "La lunghezza del buffer deve essere un multiplo di 512" #: ports/stm/common-hal/sdioio/SDCard.c msgid "Buffer must be a multiple of 512 bytes" -msgstr "" +msgstr "Il buffer deve essere un multiplo di 512 bytes" #: shared-bindings/bitbangio/I2C.c shared-bindings/busio/I2C.c msgid "Buffer must be at least length 1" @@ -533,40 +564,40 @@ msgstr "Il buffer deve essere lungo almeno 1" #: ports/nrf/common-hal/_bleio/PacketBuffer.c msgid "Buffer too large and unable to allocate" -msgstr "" +msgstr "Buffer troppo grande ed impossibile allocare" #: shared-bindings/_bleio/PacketBuffer.c #, c-format msgid "Buffer too short by %d bytes" -msgstr "" +msgstr "Buffer troppo piccolo di %d bytes" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c -#, fuzzy, c-format +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c +#, c-format msgid "Bus pin %d is already in use" -msgstr "DAC già in uso" +msgstr "Bus pin %d è già in uso" #: shared-bindings/_bleio/UUID.c -#, fuzzy msgid "Byte buffer must be 16 bytes." -msgstr "i buffer devono essere della stessa lunghezza" +msgstr "I buffer byte devono essere di almeno 16 bytes." #: shared-bindings/alarm/SleepMemory.c shared-bindings/nvm/ByteArray.c msgid "Bytes must be between 0 and 255." -msgstr "I byte devono essere compresi tra 0 e 255" +msgstr "I byte devono essere compresi tra 0 e 255." #: shared-bindings/aesio/aes.c msgid "CBC blocks must be multiples of 16 bytes" -msgstr "" +msgstr "I blocchi CBC devono essere multipli di 16 bytes" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c msgid "CRC or checksum was invalid" -msgstr "" +msgstr "CRC o controllo totale è risultato non valido" #: py/objtype.c msgid "Call super().__init__() before accessing native object." -msgstr "" +msgstr "Chiama super().__init__() prima di accedere ad un oggetto nativo." #: ports/esp32s2/common-hal/alarm/pin/PinAlarm.c msgid "Can only alarm on RTC IO from deep sleep." @@ -637,6 +668,10 @@ msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" "Impossibile resettare nel bootloader poiché nessun bootloader è presente." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "non si può impostare un valore quando direzione è input" @@ -658,7 +693,7 @@ msgstr "Impossibile trasferire senza i pin MOSI e MISO." msgid "Cannot unambiguously get sizeof scalar" msgstr "Impossibile ricavare la grandezza scalare di sizeof inequivocabilmente" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" @@ -741,14 +776,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "Impossibile inizializzare l'UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "" @@ -769,7 +796,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "" @@ -872,11 +899,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Canale EXTINT già in uso" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Errore nella regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -929,15 +961,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -946,11 +978,12 @@ msgid "Failed sending command." msgstr "" #: ports/nrf/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Impossibile leggere valore dell'attributo. status: 0x%02x" +msgstr "Impossibile acquisire il mutex, err 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Impossibile allocare buffer RX" @@ -959,6 +992,7 @@ msgstr "Impossibile allocare buffer RX" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -972,6 +1006,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "" @@ -989,14 +1027,18 @@ msgid "Failed to parse MP3 file" msgstr "" #: ports/nrf/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to release mutex, err 0x%04x" -msgstr "Impossibile leggere valore dell'attributo. status: 0x%02x" +msgstr "Impossibile rilasciare il mutex, err 0x%04x" #: supervisor/shared/safe_mode.c msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "File esistente" @@ -1020,7 +1062,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1039,10 +1081,6 @@ msgstr "" msgid "Group already used" msgstr "" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Gruppo pieno" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1073,15 +1111,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1098,10 +1136,23 @@ msgstr "" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1158,6 +1209,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Pin %q non valido" @@ -1184,8 +1236,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Frequenza PWM non valida" @@ -1203,7 +1261,8 @@ msgstr "Argomento non valido" msgid "Invalid bits per value" msgstr "bits per valore invalido" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c #, fuzzy msgid "Invalid buffer size" msgstr "lunghezza del buffer non valida" @@ -1234,14 +1293,10 @@ msgstr "File non valido" msgid "Invalid format chunk size" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "" @@ -1280,17 +1335,13 @@ msgstr "Pin non valido per il canale destro" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Pin non validi" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1312,7 +1363,7 @@ msgstr "" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1320,10 +1371,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1337,14 +1384,11 @@ msgstr "Tipo di servizio non valido" msgid "Invalid wave file" msgstr "File wave non valido" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "" @@ -1390,14 +1434,6 @@ msgstr "Valore massimo di x quando rispachiato è %d" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1450,6 +1486,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1469,9 +1509,15 @@ msgstr "Nessun DAC sul chip" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Nessun canale DMA trovato" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1530,24 +1576,20 @@ msgstr "" msgid "No hardware support on pin" msgstr "Nessun supporto hardware sul pin" -#: shared-bindings/aesio/aes.c -msgid "No key was specified" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" +#: shared-bindings/aesio/aes.c +msgid "No key was specified" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." +#: shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" #: shared-bindings/wifi/Radio.c @@ -1558,6 +1600,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1575,13 +1623,18 @@ msgid "No timer available" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c #, fuzzy @@ -1614,13 +1667,10 @@ msgid "Odd parity is not supported" msgstr "operazione I2C non supportata" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1670,10 +1720,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "L'oversampling deve essere multiplo di 8." @@ -1697,8 +1756,15 @@ msgstr "" "frequenza PWM frequency non è scrivibile quando variable_frequency è " "impostato nel costruttore a False." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "" @@ -1734,6 +1800,10 @@ msgstr "Il pin non ha capacità di ADC" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "" @@ -1750,6 +1820,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c #, fuzzy msgid "Plus any modules on the filesystem\n" @@ -1822,6 +1900,10 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1829,6 +1911,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "calibrazione RTC non supportata su questa scheda" @@ -1837,7 +1920,7 @@ msgid "RTC is not supported on this board" msgstr "RTC non supportato su questa scheda" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "" @@ -1895,12 +1978,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA o SCL necessitano un pull-up" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1938,14 +2015,6 @@ msgstr "" msgid "Scan already in progess. Stop with stop_scan." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1994,6 +2063,14 @@ msgstr "Suddivisione con sotto-catture" msgid "Stack size must be at least 256" msgstr "La dimensione dello stack deve essere almeno 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Metodi mancanti readinto() o write() allo stream." @@ -2078,16 +2155,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Per uscire resettare la scheda senza " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "" @@ -2100,7 +2173,7 @@ msgid "Too many displays" msgstr "Troppi schermi" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2127,10 +2200,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "" @@ -2157,6 +2226,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Ipossibilitato ad allocare buffer per la conversione con segno" @@ -2195,7 +2266,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "indentazione inaspettata" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2221,7 +2292,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2250,7 +2321,7 @@ msgstr "tipo di bitmap non supportato" msgid "Unsupported format" msgstr "Formato non supportato" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Operazione non supportata" @@ -2276,10 +2347,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Le funzioni Viper non supportano più di 4 argomenti al momento" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2359,11 +2426,6 @@ msgstr "un oggetto byte-like è richiesto" msgid "abort() called" msgstr "abort() chiamato" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "l'indirizzo %08x non è allineato a %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "indirizzo fuori limite" @@ -2372,15 +2434,19 @@ msgstr "indirizzo fuori limite" msgid "addresses is empty" msgstr "gli indirizzi sono vuoti" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "l'argomento è una sequenza vuota" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2388,10 +2454,6 @@ msgstr "" msgid "argument has wrong type" msgstr "il tipo dell'argomento è errato" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2401,7 +2463,8 @@ msgstr "discrepanza di numero/tipo di argomenti" msgid "argument should be a '%q' not a '%q'" msgstr "l'argomento dovrebbe essere un '%q' e non un '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2414,11 +2477,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2426,15 +2489,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "attributi non ancora supportati" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2459,8 +2522,8 @@ msgid "binary op %q not implemented" msgstr "operazione binaria %q non implementata" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "i bit devono essere 7, 8 o 9" +msgid "bits must be in range 5 to 9" +msgstr "" #: shared-bindings/audiomixer/Mixer.c #, fuzzy @@ -2472,15 +2535,11 @@ msgstr "i bit devono essere 7, 8 o 9" msgid "branch not in range" msgstr "argomento di chr() non è in range(256)" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2498,7 +2557,7 @@ msgstr "slice del buffer devono essere della stessa lunghezza" msgid "buffer too small" msgstr "buffer troppo piccolo" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2565,6 +2624,10 @@ msgstr "impossibile assegnare all'espressione" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "impossibile convertire l'oggetto '%q' implicitamente in %q" @@ -2573,6 +2636,10 @@ msgstr "impossibile convertire l'oggetto '%q' implicitamente in %q" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "non è possibile convertire a int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "impossibile convertire a stringa implicitamente" @@ -2691,6 +2758,10 @@ msgstr "argomento di chr() non è in range(256)" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2737,19 +2808,19 @@ msgstr "la costante deve essere un intero" msgid "conversion to object" msgstr "conversione in oggetto" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2757,15 +2828,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2805,14 +2876,18 @@ msgstr "destination_length deve essere un int >= 0" msgid "dict update sequence has wrong length" msgstr "sequanza di aggiornamento del dizionario ha la lunghezza errata" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2921,7 +2996,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2929,11 +3004,11 @@ msgstr "" msgid "filesystem must provide mount method" msgstr "il filesystem deve fornire un metodo di mount" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2941,11 +3016,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2957,7 +3028,7 @@ msgstr "" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2978,8 +3049,8 @@ msgid "full" msgstr "pieno" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "la funzione non prende argomenti nominati" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -2990,7 +3061,7 @@ msgstr "la funzione prevede al massimo %d argmoneti, ma ne ha ricevuti %d" msgid "function got multiple values for argument '%q'" msgstr "la funzione ha ricevuto valori multipli per l'argomento '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -3034,6 +3105,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic deve essere lunga 2048 byte" @@ -3066,8 +3141,9 @@ msgstr "padding incorretto" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "indice fuori intervallo" @@ -3079,7 +3155,7 @@ msgstr "gli indici devono essere interi" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3099,7 +3175,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3107,15 +3183,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3131,23 +3207,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3159,7 +3235,7 @@ msgstr "il secondo argomanto di int() deve essere >= 2 e <= 36" msgid "integer required" msgstr "intero richiesto" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3172,14 +3248,33 @@ msgstr "" msgid "invalid arguments" msgstr "argomenti non validi" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "certificato non valido" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "indice dupterm non valido" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "formato non valido" @@ -3221,10 +3316,6 @@ msgstr "sintassi invalida per l'intero con base %d" msgid "invalid syntax for number" msgstr "sintassi invalida per il numero" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "il primo argomento di issubclass() deve essere una classe" @@ -3235,11 +3326,7 @@ msgstr "" "il secondo argomento di issubclass() deve essere una classe o una tupla di " "classi" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3310,11 +3397,7 @@ msgstr "map buffer troppo piccolo" msgid "math domain error" msgstr "errore di dominio matematico" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3336,15 +3419,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "profondità massima di ricorsione superata" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3357,11 +3440,15 @@ msgstr "allocazione di memoria fallita, allocando %u byte" msgid "memory allocation failed, heap is locked" msgstr "allocazione di memoria fallita, l'heap è bloccato" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "modulo non trovato" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3406,6 +3493,10 @@ msgstr "yield nativo" msgid "need more than %d values to unpack" msgstr "necessari più di %d valori da scompattare" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "potenza negativa senza supporto per float" @@ -3480,10 +3571,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3554,7 +3641,7 @@ msgstr "" msgid "odd-length string" msgstr "stringa di lunghezza dispari" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3584,8 +3671,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "solo slice con step=1 (aka None) sono supportate" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3593,7 +3680,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3611,11 +3698,19 @@ msgid "ord() expected a character, but string of length %d found" msgstr "" "ord() aspettava un carattere, ma ha ricevuto una stringa di lunghezza %d" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3636,10 +3731,6 @@ msgstr "la palette deve essere lunga 32 byte" msgid "palette_index should be an int" msgstr "palette_index deve essere un int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parametri devono essere i registri in sequenza da a2 a a5" @@ -3649,7 +3740,7 @@ msgstr "parametri devono essere i registri in sequenza da a2 a a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "parametri devono essere i registri in sequenza da a2 a a5" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c #, fuzzy msgid "pixel coordinates out of bounds" msgstr "indirizzo fuori limite" @@ -3673,11 +3764,16 @@ msgstr "pop sun un PulseIn vuoto" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "il terzo argomento di pow() non può essere 0" @@ -3688,12 +3784,17 @@ msgstr "pow() con 3 argomenti richiede interi" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3701,6 +3802,7 @@ msgstr "pow() con 3 argomenti richiede interi" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3712,6 +3814,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3728,7 +3838,7 @@ msgstr "overflow della coda" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3763,7 +3873,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3780,6 +3890,7 @@ msgstr "" "'H', 'b' o 'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "frequenza di campionamento fuori intervallo" @@ -3811,7 +3922,7 @@ msgstr "segno non permesso nello spcificatore di formato 'c' della stringa" msgid "single '}' encountered in format string" msgstr "'}' singolo presente nella stringa di formattazione" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3835,23 +3946,23 @@ msgstr "small int overflow" msgid "soft reboot\n" msgstr "soft reboot\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3963,7 +4074,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "troppi argomenti forniti con il formato specificato" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3976,18 +4087,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "troppi valori da scompattare (%d attesi)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupla/lista ha la lunghezza sbagliata" @@ -4057,9 +4164,9 @@ msgid "unindent does not match any outer indentation level" msgstr "" #: py/objstr.c -#, fuzzy, c-format +#, c-format msgid "unknown conversion specifier %c" -msgstr "specificatore di conversione %s sconosciuto" +msgstr "specificatore di conversione %c sconosciuto" #: py/objstr.c msgid "unknown format code '%c' for object of type '%q'" @@ -4069,7 +4176,7 @@ msgstr "" msgid "unknown type" msgstr "tipo sconosciuto" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "tipo '%q' sconosciuto" @@ -4122,14 +4229,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4138,6 +4237,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4150,7 +4254,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4158,7 +4262,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4174,7 +4279,7 @@ msgstr "numero di valori da scompattare non corretto" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4200,18 +4305,39 @@ msgstr "indirizzo fuori limite" msgid "zero step" msgstr "zero step" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Le funzioni Viper non supportano più di 4 argomenti al momento" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "l'indirizzo %08x non è allineato a %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "la funzione non prende argomenti nominati" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Provo l'allocazione quando MicroPython VM non è attivo." + +#~ msgid "Group full" +#~ msgstr "Gruppo pieno" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "i bit devono essere 7, 8 o 9" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA o SCL necessitano un pull-up" + #~ msgid "tuple index out of range" #~ msgstr "indice della tupla fuori intervallo" @@ -4277,9 +4403,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "non è possibile convertire a float" -#~ msgid "can't convert to int" -#~ msgstr "non è possibile convertire a int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "oggetto '%s' non è una tupla o una lista" diff --git a/locale/ja.po b/locale/ja.po index c139ec3cc8a18..0d3e93d1c27a2 100644 --- a/locale/ja.po +++ b/locale/ja.po @@ -78,6 +78,7 @@ msgstr "%qは使用中" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -107,6 +108,7 @@ msgstr "%qは1以上でなければなりません" msgid "%q must be a tuple of length 2" msgstr "%qは長さ2のタプルでなければなりません" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q が範囲外" @@ -337,9 +339,14 @@ msgid "All SPI peripherals are in use" msgstr "全てのSPI周辺機器が使用中" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "全てのUART周辺機器が使用中" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "全てのイベントチャネルが使用中" @@ -368,6 +375,7 @@ msgstr "このピン用の全てのタイマが使用中" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "全てのタイマーが使用中" @@ -408,6 +416,10 @@ msgstr "AnalogOutは16ビットです。値は65536以下でなければなり msgid "AnalogOut not supported on given pin" msgstr "指定のピンはAnalogOutに対応していません" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -431,8 +443,8 @@ msgid "Attempt to allocate %d blocks" msgstr "%d個のブロックの確保を試みました" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "MicroPython VMの非実行時にヒープ確保を試みました" +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -459,6 +471,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "最低のフレームレート未満" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "bit clockとword selectはクロックユニットを共有しなければなりません" @@ -500,6 +516,10 @@ msgstr "Brightnessは調整可能ではありません" msgid "Buffer + offset too small %d %d %d" msgstr "buffer + offsetが小さすぎます %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -516,6 +536,7 @@ msgid "Buffer is too small" msgstr "バッファが小さすぎます" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "バッファ長%dは大きすぎます。%d以下でなければなりません" @@ -545,6 +566,7 @@ msgstr "バッファが %d バイト足りません" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Busピン%dはすでに使用中" @@ -638,6 +660,10 @@ msgstr "USBがアクティブの時に'/'を再マウントできません" msgid "Cannot reset into bootloader because no bootloader is present." msgstr "ブートローダが存在しないためブートローダへとリセットできません" +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "方向がinputのときは値を設定できません" @@ -659,7 +685,7 @@ msgstr "MOSIピンとMISOピンなしに転送できません" msgid "Cannot unambiguously get sizeof scalar" msgstr "スカラのサイズを曖昧さなしに取得できません" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "使用中のタイマー上では周波数を変えられません" @@ -743,14 +769,6 @@ msgstr "SDカードを初期化できません" msgid "Could not initialize UART" msgstr "UARTを初期化できません" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "チャネルを初期化できません" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "タイマーを初期化できません" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "チャネルを再初期化できません" @@ -771,7 +789,7 @@ msgstr "" msgid "Could not set address" msgstr "アドレスをセットできません" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "PWMをスタートできません" @@ -872,11 +890,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "EXTINTチャネルはすでに使用されています" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "正規表現にエラーがあります" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -927,15 +950,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "FFTはndarrayでのみ使えます" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -949,6 +972,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "ミューテックスの取得に失敗。エラー 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "RXバッファの確保に失敗" @@ -957,6 +981,7 @@ msgstr "RXバッファの確保に失敗" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -970,6 +995,10 @@ msgstr "Wi-Fiのメモリの確保に失敗" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "接続失敗: 内部エラー" @@ -995,6 +1024,10 @@ msgstr "ミューテックスの開放に失敗。エラー 0x%04x" msgid "Failed to write internal flash." msgstr "内部フラッシュ書き込みに失敗" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "ファイルが存在します" @@ -1018,7 +1051,7 @@ msgstr "非対応の形式" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "このタイマーを使う既存のPWMOutと周波数を一致させる必要があります" @@ -1037,10 +1070,6 @@ msgstr "" msgid "Group already used" msgstr "グループはすでに使われています" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "グループが一杯" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1071,15 +1100,15 @@ msgstr "" msgid "I2SOut not available" msgstr "I2SOutが利用できません" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IVは%dバイト長でなければなりません" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1096,10 +1125,23 @@ msgstr "バッファサイズが正しくありません" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1156,6 +1198,7 @@ msgstr "不正な %q" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "不正な%qピン" @@ -1182,8 +1225,14 @@ msgstr "不正なBSSID" msgid "Invalid DAC pin supplied" msgstr "不正なDACピンが与えられました" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "無効なPWM周波数" @@ -1201,7 +1250,8 @@ msgstr "不正な引数" msgid "Invalid bits per value" msgstr "不正なbits per value" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "不正なバッファサイズ" @@ -1230,14 +1280,10 @@ msgstr "不正なファイル" msgid "Invalid format chunk size" msgstr "フォーマットチャンクのサイズが不正" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "不正な周波数" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "不正な周波数が与えられました" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "不正なメモリアクセス" @@ -1276,17 +1322,13 @@ msgstr "右チャネルのピンが不正" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "ピンが不正" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "PWMOutのピンが不正" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1308,7 +1350,7 @@ msgstr "不正なsecurity_mode" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1316,10 +1358,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "不正なボイス" @@ -1332,14 +1370,11 @@ msgstr "不正なボイス数" msgid "Invalid wave file" msgstr "不正なwaveファイル" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "不正なワード/ビット長" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "Keyの長さは、16, 24, 32バイトのいずれかでなければなりません" @@ -1385,14 +1420,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLRジャンプ失敗。メモリ破壊の可能性あり" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython致命的エラー" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "マイクのスタートアップディレイは 0.0 から 1.0 の間でなければなりません" @@ -1444,6 +1471,10 @@ msgstr "MISOピンまたはMOSIピンが必要" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "%d個でなく6の倍数個のrgbピンを使ってください" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1463,9 +1494,15 @@ msgstr "チップにDACがありません" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "DMAチャネルが見つかりません" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1524,6 +1561,14 @@ msgstr "clkピンにハードウェア対応がありません" msgid "No hardware support on pin" msgstr "ピンにハードウェア対応がありません" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "キーが指定されていません" @@ -1532,18 +1577,6 @@ msgstr "キーが指定されていません" msgid "No long integer support" msgstr "long integerに対応していません" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "使えるチャネルがもうありません" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "使えるタイマーがもうありません" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "このピンには使えるタイマーがもうありません" - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "" @@ -1552,6 +1585,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "ピンにプルダウンがありません。1Mオーム推奨" @@ -1569,13 +1608,18 @@ msgid "No timer available" msgstr "利用できるタイマーなし" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "不正なIP文字列です" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1606,13 +1650,10 @@ msgid "Odd parity is not supported" msgstr "奇数パリティには対応していません" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "8または16ビットの " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1662,10 +1703,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "オーバーサンプルは8の倍数でなければなりません" @@ -1685,8 +1735,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "PWM周波数は生成時のvariable_frequencyがFalseのとき書き換え不可" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBusにはまだ対応していません" @@ -1722,6 +1779,10 @@ msgstr "ピンにADCの能力がありません" msgid "Pin is input only" msgstr "ピンは入力専用" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "ピンはハードウェア割り込みに対応していなければなりません" @@ -1738,6 +1799,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "" @@ -1809,6 +1878,10 @@ msgstr "RNG解体エラー" msgid "RNG Init Error" msgstr "乱数生成器の初期化エラー" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1816,6 +1889,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "このボードはRTCのキャリブレーションに非対応" @@ -1824,7 +1898,7 @@ msgid "RTC is not supported on this board" msgstr "このボードはRTCに対応していません" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS/CTS/RS485はこのデバイスでは未対応" @@ -1881,12 +1955,6 @@ msgstr "セーフモードで実行中! " msgid "SD card CSD format not supported" msgstr "SDカードのCSDフォーマットは非対応" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDAとSCLにプルアップが必要" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1922,14 +1990,6 @@ msgstr "サンプルレートは%d以下でなければなりません" msgid "Scan already in progess. Stop with stop_scan." msgstr "既にスキャン進行中。stop_scanで停止してください" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "選択されたCTSピンが不正" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "選択されたRTSピンが正しくありません" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1978,6 +2038,14 @@ msgstr "" msgid "Stack size must be at least 256" msgstr "スタックサイズは少なくとも256以上でなければなりません" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "ストリームにreadinto()またはwrite()メソッドがありません" @@ -2068,16 +2136,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "タイムアウトが長すぎです。最大のタイムアウト長は%d秒" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "サンプルのチャンネル数が多すぎます" @@ -2090,7 +2154,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2117,10 +2181,6 @@ msgstr "UARTの初期化エラー" msgid "UART Re-init error" msgstr "UARTの再初期化エラー" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "UART書き込みエラー" @@ -2148,6 +2208,8 @@ msgstr "UUIDの値がstr, int, bufferのいずれでもありません" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "" @@ -2185,7 +2247,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "想定されていないnrfx UUID型" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2211,8 +2273,8 @@ msgstr "不明なセキュリティエラー: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "不明なソフトデバイスエラー: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2239,7 +2301,7 @@ msgstr "" msgid "Unsupported format" msgstr "非対応の形式" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "非対応の操作" @@ -2265,10 +2327,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "電圧読み取りがタイムアウト" @@ -2348,11 +2406,6 @@ msgstr "bytes-likeオブジェクトが必要" msgid "abort() called" msgstr "abort()が呼ばれました" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "アドレスが範囲外" @@ -2361,15 +2414,19 @@ msgstr "アドレスが範囲外" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "argsortの引数はndarrayでなければなりません" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2377,10 +2434,6 @@ msgstr "" msgid "argument has wrong type" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "引数はndarrayでなければなりません" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2390,7 +2443,8 @@ msgstr "" msgid "argument should be a '%q' not a '%q'" msgstr "引数には '%q' が必要('%q' ではなく)" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "引数はndarrayでなければなりません" @@ -2403,11 +2457,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "右辺にはarray/bytesが必要" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2415,15 +2469,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "属性は未対応です" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2448,8 +2502,8 @@ msgid "binary op %q not implemented" msgstr "" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bitsは7, 8, 9のいずれかでなければなりません" +msgid "bits must be in range 5 to 9" +msgstr "" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2459,15 +2513,11 @@ msgstr "bits_per_sampleは8または16でなければなりません" msgid "branch not in range" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "バッファはbytes-likeオブジェクトでなければなりません" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2484,7 +2534,7 @@ msgstr "バッファのスライスは同じ長さでなければなりません msgid "buffer too small" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2550,6 +2600,10 @@ msgstr "式には代入できません" msgid "can't convert %q to %q" msgstr "%qを%qに変換できません" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "オブジェクト '%q' を %q に暗黙に変換できません" @@ -2558,6 +2612,10 @@ msgstr "オブジェクト '%q' を %q に暗黙に変換できません" msgid "can't convert to %q" msgstr "%q に変換できません" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2676,6 +2734,10 @@ msgstr "" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2722,19 +2784,19 @@ msgstr "定数は整数でなければなりません" msgid "conversion to object" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "convolve引数には1次元arrayが必要" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "convolve引数はndarrayでなければなりません" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "ヴァンデルモンド行列の逆行列を求められません" @@ -2742,15 +2804,15 @@ msgstr "ヴァンデルモンド行列の逆行列を求められません" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "dataはイテレート可能でなければなりません" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "dataは同じ長さでなければなりません" @@ -2789,14 +2851,18 @@ msgstr "desitination_lengthは正の整数でなければなりません" msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "引数はndarrayでなければなりません" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2904,7 +2970,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: 1つだけの'}'は許されません" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "fileはバイトモードで開かれたファイルでなければなりません" @@ -2912,11 +2978,11 @@ msgstr "fileはバイトモードで開かれたファイルでなければな msgid "filesystem must provide mount method" msgstr "filesystemはmountメソッドを提供しなければなりません" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "1つ目の引数は呼び出し可能でなければなりません" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "1つ目の引数は関数でなければなりません" @@ -2924,11 +2990,7 @@ msgstr "1つ目の引数は関数でなければなりません" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "1つ目の引数はイテレート可能でなければなりません" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "1つ目の引数はndarrayでなければなりません" @@ -2940,7 +3002,7 @@ msgstr "superの第1引数は型でなければなりません" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "flipの引数はndarrayでなければなりません" @@ -2961,7 +3023,7 @@ msgid "full" msgstr "" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -2973,7 +3035,7 @@ msgstr "" msgid "function got multiple values for argument '%q'" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -3016,6 +3078,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphicは2048バイトでなければなりません" @@ -3048,8 +3114,9 @@ msgstr "" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "インデクスが範囲外" @@ -3062,7 +3129,7 @@ msgid "indices must be integers, slices, or Boolean lists" msgstr "" "インデクスは、整数、スライス、boolのリストのいずれかでなければなりません" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3082,7 +3149,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "入力array長は2の累乗でなければなりません" @@ -3090,15 +3157,15 @@ msgstr "入力array長は2の累乗でなければなりません" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "入力行列が非対称" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "入力が非正則行列" @@ -3114,23 +3181,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "入力は正方行列でなければなりません" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "入力はtuple, list, range, ndarrayでなければなりません" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3142,7 +3209,7 @@ msgstr "int()の第2引数は2以上36以下でなければなりません" msgid "integer required" msgstr "整数が必要" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3155,14 +3222,33 @@ msgstr "intervalは%s-%sの範囲でなければなりません" msgid "invalid arguments" msgstr "不正な引数" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "不正な証明書" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "不正なduptermインデクス" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "" @@ -3204,10 +3290,6 @@ msgstr "" msgid "invalid syntax for number" msgstr "数字として不正な構文" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass()の第1引数はクラスでなければなりません" @@ -3216,11 +3298,7 @@ msgstr "issubclass()の第1引数はクラスでなければなりません" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass()の第2引数はクラスかクラスのタプルでなければなりません" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "iterableが同じ長さではありません" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "収束しません" @@ -3288,11 +3366,7 @@ msgstr "" msgid "math domain error" msgstr "定義域エラー" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "行列の次元が一致しません" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "正定値行列ではありません" @@ -3314,15 +3388,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "最大の再帰深度を超えました" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3335,11 +3409,15 @@ msgstr "" msgid "memory allocation failed, heap is locked" msgstr "メモリ確保に失敗。ヒープがロックされています" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "モジュールが見つかりません" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3384,6 +3462,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "アンパックする値は%d個では足りません" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3457,10 +3539,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "128ビットのUUIDではありません" @@ -3529,7 +3607,7 @@ msgstr "" msgid "odd-length string" msgstr "奇数長の文字列" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3558,8 +3636,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3567,7 +3645,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "この演算はndarray上で実装されていません" @@ -3584,11 +3662,19 @@ msgstr "ord()は1文字を受け取ります" msgid "ord() expected a character, but string of length %d found" msgstr "ord()は1文字を要求しますが、長さ %d の文字列が与えられました" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "ソースが範囲外" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3609,10 +3695,6 @@ msgstr "パレットの長さは32バイトでなければなりません" msgid "palette_index should be an int" msgstr "palette_indexには整数が必要" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "引数アノテーションは識別子でなければなりません" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3621,7 +3703,7 @@ msgstr "" msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "" @@ -3646,11 +3728,16 @@ msgstr "" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "pow()の3つ目の引数は0にできません" @@ -3661,12 +3748,17 @@ msgstr "pow()の第3引数には整数が必要" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3674,6 +3766,7 @@ msgstr "pow()の第3引数には整数が必要" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3685,6 +3778,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3701,7 +3802,7 @@ msgstr "キューがオーバーフローしました" msgid "raw f-strings are not implemented" msgstr "raw f-文字列は実装されていません" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "実数部と虚数部は同じ長さでなければなりません" @@ -3736,7 +3837,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins[%d]はクロックと同じポートではありません" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3752,6 +3853,7 @@ msgstr "" "sample_source バッファには bytearray または 'h','H','b','B'型のarrayが必要" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "サンプリングレートが範囲外" @@ -3783,7 +3885,7 @@ msgstr "整数フォーマット指定子'c'で符号は使えません" msgid "single '}' encountered in format string" msgstr "文字列フォーマット中に孤立した '}' があります" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3807,23 +3909,23 @@ msgstr "small int オーバーフロー" msgid "soft reboot\n" msgstr "ソフトリブート\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3933,7 +4035,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "指定された書式に対して引数が多すぎます" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3946,18 +4048,14 @@ msgstr "インデクスが多すぎます" msgid "too many values to unpack (expected %d)" msgstr "アンパックする値が多すぎます (%d個を期待)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "trapzは同じ長さの1次元arrayに対して定義されています" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "タプル/リストの長さが正しくありません" @@ -4039,7 +4137,7 @@ msgstr "型'%q'のオブジェクトに対する不明な書式コード'%c'" msgid "unknown type" msgstr "不明な型" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "不明な型 '%q'" @@ -4092,14 +4190,6 @@ msgstr "値は%dバイトに収まらなければなりません" msgid "value_count must be > 0" msgstr "value_countは0より大きくなければなりません" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4108,6 +4198,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "watchdogのtimeoutは0以上でなければなりません" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4120,7 +4215,7 @@ msgstr "" msgid "window must be <= interval" msgstr "windowはinterval以下でなければなりません" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4128,7 +4223,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4144,7 +4240,7 @@ msgstr "アンパックする値の個数が不正です" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4168,18 +4264,84 @@ msgstr "yが範囲外" msgid "zero step" msgstr "ステップが0" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "ziはndarrayでなければなりません" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "ziはfloat値でなければなりません" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "引数アノテーションは識別子でなければなりません" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "バッファはbytes-likeオブジェクトでなければなりません" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "MicroPython VMの非実行時にヒープ確保を試みました" + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLRジャンプ失敗。メモリ破壊の可能性あり" + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython致命的エラー" + +#~ msgid "argument must be ndarray" +#~ msgstr "引数はndarrayでなければなりません" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "行列の次元が一致しません" + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "不明なソフトデバイスエラー: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "1つ目の引数はイテレート可能でなければなりません" + +#~ msgid "iterables are not of the same length" +#~ msgstr "iterableが同じ長さではありません" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "選択されたCTSピンが不正" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "選択されたRTSピンが正しくありません" + +#~ msgid "Could not initialize channel" +#~ msgstr "チャネルを初期化できません" + +#~ msgid "Could not initialize timer" +#~ msgstr "タイマーを初期化できません" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "不正な周波数が与えられました" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "PWMOutのピンが不正" + +#~ msgid "No more channels available" +#~ msgstr "使えるチャネルがもうありません" + +#~ msgid "No more timers available" +#~ msgstr "使えるタイマーがもうありません" + +#~ msgid "No more timers available on this pin." +#~ msgstr "このピンには使えるタイマーがもうありません" + +#~ msgid "Group full" +#~ msgstr "グループが一杯" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bitsは7, 8, 9のいずれかでなければなりません" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDAとSCLにプルアップが必要" + #~ msgid "" #~ "\n" #~ "Code done running. Waiting for reload.\n" diff --git a/locale/ko.po b/locale/ko.po index 54e57f191fc37..7adda96b93283 100644 --- a/locale/ko.po +++ b/locale/ko.po @@ -74,6 +74,7 @@ msgstr "%q 사용 중입니다" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -103,6 +104,7 @@ msgstr "%q 는 >=1이어야합니다" msgid "%q must be a tuple of length 2" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "" @@ -333,9 +335,14 @@ msgid "All SPI peripherals are in use" msgstr "사용중인 모든 SPI주변 기기" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "사용중인 모든 UART주변 기기" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "" @@ -364,6 +371,7 @@ msgstr "핀의 모든 타이머가 사용 중입니다" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "모든 타이머가 사용 중입니다" @@ -404,6 +412,10 @@ msgstr "" msgid "AnalogOut not supported on given pin" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -427,7 +439,7 @@ msgid "Attempt to allocate %d blocks" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" #: shared-bindings/wifi/Radio.c @@ -455,6 +467,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "" @@ -496,6 +512,10 @@ msgstr "밝기를 조절할 수 없습니다" msgid "Buffer + offset too small %d %d %d" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -512,6 +532,7 @@ msgid "Buffer is too small" msgstr "" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "" @@ -541,6 +562,7 @@ msgstr "" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "" @@ -632,6 +654,10 @@ msgstr "" msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "" @@ -653,7 +679,7 @@ msgstr "" msgid "Cannot unambiguously get sizeof scalar" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "" @@ -735,14 +761,6 @@ msgstr "" msgid "Could not initialize UART" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "" @@ -763,7 +781,7 @@ msgstr "" msgid "Could not set address" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "" @@ -864,11 +882,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Regex에 오류가 있습니다." -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -919,15 +942,15 @@ msgstr "" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -941,6 +964,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "" @@ -949,6 +973,7 @@ msgstr "" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -962,6 +987,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "" @@ -987,6 +1016,10 @@ msgstr "" msgid "Failed to write internal flash." msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "" @@ -1010,7 +1043,7 @@ msgstr "" msgid "Framebuffer requires %d bytes" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1029,10 +1062,6 @@ msgstr "" msgid "Group already used" msgstr "" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1063,15 +1092,15 @@ msgstr "" msgid "I2SOut not available" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1086,10 +1115,23 @@ msgstr "" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1146,6 +1188,7 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "" @@ -1172,8 +1215,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "" @@ -1191,7 +1240,8 @@ msgstr "" msgid "Invalid bits per value" msgstr "" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "" @@ -1220,14 +1270,10 @@ msgstr "파일이 유효하지 않습니다" msgid "Invalid format chunk size" msgstr "형식 청크 크기가 잘못되었습니다" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "" @@ -1266,17 +1312,13 @@ msgstr "오른쪽 채널 핀이 잘못되었습니다" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "핀이 유효하지 않습니다" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1298,7 +1340,7 @@ msgstr "" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1306,10 +1348,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1322,14 +1360,11 @@ msgstr "" msgid "Invalid wave file" msgstr "" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "" @@ -1375,14 +1410,6 @@ msgstr "" msgid "Messages limited to 8 bytes" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "" - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1434,6 +1461,10 @@ msgstr "" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1453,9 +1484,15 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1514,24 +1551,20 @@ msgstr "" msgid "No hardware support on pin" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "No key was specified" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" +#: shared-bindings/aesio/aes.c +msgid "No key was specified" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." +#: shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" #: shared-bindings/wifi/Radio.c @@ -1542,6 +1575,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1559,13 +1598,18 @@ msgid "No timer available" msgstr "" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1594,13 +1638,10 @@ msgid "Odd parity is not supported" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1650,10 +1691,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "" @@ -1672,8 +1722,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "" @@ -1709,6 +1766,10 @@ msgstr "" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "" @@ -1725,6 +1786,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "" @@ -1796,6 +1865,10 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1803,6 +1876,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "" @@ -1811,7 +1885,7 @@ msgid "RTC is not supported on this board" msgstr "" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "" @@ -1868,12 +1942,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1909,14 +1977,6 @@ msgstr "" msgid "Scan already in progess. Stop with stop_scan." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1965,6 +2025,14 @@ msgstr "" msgid "Stack size must be at least 256" msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "" @@ -2049,16 +2117,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "" @@ -2071,7 +2135,7 @@ msgid "Too many displays" msgstr "" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2098,10 +2162,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "" @@ -2129,6 +2189,8 @@ msgstr "" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "" @@ -2166,7 +2228,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2192,7 +2254,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2220,7 +2282,7 @@ msgstr "" msgid "Unsupported format" msgstr "" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "" @@ -2246,10 +2308,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2329,11 +2387,6 @@ msgstr "" msgid "abort() called" msgstr "" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "" @@ -2342,15 +2395,19 @@ msgstr "" msgid "addresses is empty" msgstr "" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2358,10 +2415,6 @@ msgstr "" msgid "argument has wrong type" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2371,7 +2424,8 @@ msgstr "" msgid "argument should be a '%q' not a '%q'" msgstr "" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2384,11 +2438,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2396,15 +2450,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2429,8 +2483,8 @@ msgid "binary op %q not implemented" msgstr "" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "비트(bits)는 7, 8 또는 9 여야합니다" +msgid "bits must be in range 5 to 9" +msgstr "" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2440,15 +2494,11 @@ msgstr "bits_per_sample은 8 또는 16이어야합니다." msgid "branch not in range" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2465,7 +2515,7 @@ msgstr "" msgid "buffer too small" msgstr "" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2531,6 +2581,10 @@ msgstr "" msgid "can't convert %q to %q" msgstr "" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "" @@ -2539,6 +2593,10 @@ msgstr "" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "" @@ -2657,6 +2715,10 @@ msgstr "" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2701,19 +2763,19 @@ msgstr "" msgid "conversion to object" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2721,15 +2783,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2766,14 +2828,18 @@ msgstr "" msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2881,7 +2947,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "" @@ -2889,11 +2955,11 @@ msgstr "" msgid "filesystem must provide mount method" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "" @@ -2901,11 +2967,7 @@ msgstr "" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2917,7 +2979,7 @@ msgstr "" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2938,7 +3000,7 @@ msgid "full" msgstr "완전한(full)" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "" #: py/argcheck.c @@ -2950,7 +3012,7 @@ msgstr "" msgid "function got multiple values for argument '%q'" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -2993,6 +3055,10 @@ msgstr "" msgid "generator ignored GeneratorExit" msgstr "" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "" @@ -3025,8 +3091,9 @@ msgstr "" msgid "index is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "" @@ -3038,7 +3105,7 @@ msgstr "" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "" @@ -3058,7 +3125,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "" @@ -3066,15 +3133,15 @@ msgstr "" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3090,23 +3157,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3118,7 +3185,7 @@ msgstr "" msgid "integer required" msgstr "정수가 필요합니다" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3131,14 +3198,33 @@ msgstr "" msgid "invalid arguments" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "cert가 유효하지 않습니다" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "Dupterm index가 유효하지 않습니다" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "형식가 유효하지 않습니다" @@ -3180,10 +3266,6 @@ msgstr "구문(syntax)가 정수가 유효하지 않습니다" msgid "invalid syntax for number" msgstr "숫자에 대한 구문(syntax)가 유효하지 않습니다" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "" @@ -3192,11 +3274,7 @@ msgstr "" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3264,11 +3342,7 @@ msgstr "" msgid "math domain error" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3290,15 +3364,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3311,11 +3385,15 @@ msgstr "" msgid "memory allocation failed, heap is locked" msgstr "" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3360,6 +3438,10 @@ msgstr "" msgid "need more than %d values to unpack" msgstr "" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "" @@ -3433,10 +3515,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "" @@ -3505,7 +3583,7 @@ msgstr "" msgid "odd-length string" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3534,8 +3612,8 @@ msgstr "" msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "" @@ -3543,7 +3621,7 @@ msgstr "" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3560,11 +3638,19 @@ msgstr "" msgid "ord() expected a character, but string of length %d found" msgstr "" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3585,10 +3671,6 @@ msgstr "" msgid "palette_index should be an int" msgstr "" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "" @@ -3597,7 +3679,7 @@ msgstr "" msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "" @@ -3620,11 +3702,16 @@ msgstr "" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "" @@ -3635,12 +3722,17 @@ msgstr "" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3648,6 +3740,7 @@ msgstr "" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3659,6 +3752,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3675,7 +3776,7 @@ msgstr "" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "" @@ -3710,7 +3811,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3725,6 +3826,7 @@ msgid "" msgstr "" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "" @@ -3756,7 +3858,7 @@ msgstr "" msgid "single '}' encountered in format string" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3780,23 +3882,23 @@ msgstr "" msgid "soft reboot\n" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "" @@ -3906,7 +4008,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3919,18 +4021,14 @@ msgstr "" msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "" @@ -4012,7 +4110,7 @@ msgstr "" msgid "unknown type" msgstr "" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "" @@ -4065,14 +4163,6 @@ msgstr "" msgid "value_count must be > 0" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4081,6 +4171,11 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "" @@ -4093,7 +4188,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4101,7 +4196,8 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "" @@ -4117,7 +4213,7 @@ msgstr "" msgid "wrong operand type" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "" @@ -4141,18 +4237,21 @@ msgstr "" msgid "zero step" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "비트(bits)는 7, 8 또는 9 여야합니다" + #~ msgid "" #~ "\n" #~ "Code done running. Waiting for reload.\n" diff --git a/locale/nl.po b/locale/nl.po index de9aed9e7d00c..abc7a00a57da4 100644 --- a/locale/nl.po +++ b/locale/nl.po @@ -76,6 +76,7 @@ msgstr "%q in gebruik" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -105,6 +106,7 @@ msgstr "%q moet >= 1 zijn" msgid "%q must be a tuple of length 2" msgstr "%q moet een tuple van lengte 2 zijn" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q buiten bereik" @@ -335,9 +337,14 @@ msgid "All SPI peripherals are in use" msgstr "Alle SPI peripherals zijn in gebruik" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Alle UART peripherals zijn in gebruik" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Alle event kanalen zijn in gebruik" @@ -366,6 +373,7 @@ msgstr "Alle timers voor deze pin zijn in gebruik" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Alle timers zijn in gebruik" @@ -406,6 +414,10 @@ msgstr "AnalogOut is slechts 16 bits. Waarde moet minder dan 65536 zijn." msgid "AnalogOut not supported on given pin" msgstr "AnalogOut niet ondersteund door gegeven pin" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -429,8 +441,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Poging om %d blokken toe te wijzen" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "heap allocatie geprobeerd terwijl MicroPython VM niet draait." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -457,6 +469,10 @@ msgstr "Baudrate wordt niet ondersteund door randapparatuur" msgid "Below minimum frame rate" msgstr "Onder de minimum frame rate" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Bit clock en word select moeten een clock eenheid delen" @@ -498,6 +514,10 @@ msgstr "Helderheid is niet aanpasbaar" msgid "Buffer + offset too small %d %d %d" msgstr "Buffer + offset te klein %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -514,6 +534,7 @@ msgid "Buffer is too small" msgstr "Buffer is te klein" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "Buffer lengte %d te groot. Het moet kleiner zijn dan %d" @@ -543,6 +564,7 @@ msgstr "Buffer is %d bytes te klein" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Bus pin %d al in gebruik" @@ -636,6 +658,10 @@ msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" "Kan niet resetten naar bootloader omdat er geen bootloader aanwezig is." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Kan de waarde niet toewijzen als de richting input is." @@ -657,7 +683,7 @@ msgstr "Kan niet overdragen zonder MOSI en MISO pinnen." msgid "Cannot unambiguously get sizeof scalar" msgstr "Kan niet ondubbelzinning sizeof scalar verkrijgen" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "Kan de frequentie van een timer die al in gebruik is niet variëren" @@ -743,14 +769,6 @@ msgstr "Kan SDCard niet initialiseren" msgid "Could not initialize UART" msgstr "Kan UART niet initialiseren" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Kan kanaal niet initialiseren" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Kan timer niet initialiseren" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Kan kanaal niet her-initialiseren" @@ -771,7 +789,7 @@ msgstr "Kon klok niet ophalen" msgid "Could not set address" msgstr "Kan adres niet zetten" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "Kan PWM niet starten" @@ -872,11 +890,16 @@ msgstr "ESP-IDF geheugen toewijzing mislukt" msgid "EXTINT channel already in use" msgstr "EXTINT kanaal al in gebruik" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Fout in regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -927,15 +950,15 @@ msgstr "Verwachtte een tuple met lengte %d, maar kreeg %d" msgid "Extended advertisements with scan response not supported." msgstr "Extended advertisements met scan antwoord niet ondersteund." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "FFT alleen voor ndarrays gedefineerd" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "FFT is alleen geïmplementeerd voor lineaire arrays" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "SSL handdruk mislukt" @@ -949,6 +972,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Fout tijdens verkrijgen mutex, err 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "RX buffer alloceren mislukt" @@ -957,6 +981,7 @@ msgstr "RX buffer alloceren mislukt" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -970,6 +995,10 @@ msgstr "Kon WiFi geheugen niet toewijzen" msgid "Failed to allocate wifi scan memory" msgstr "Kon WiFi scan geheugen niet toewijzen" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Verbinding mislukt: interne fout" @@ -995,6 +1024,10 @@ msgstr "Mislukt mutex los te laten, err 0x%04x" msgid "Failed to write internal flash." msgstr "Schrijven naar interne flash mislukt." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Bestand bestaat" @@ -1018,7 +1051,7 @@ msgstr "Formaat wordt niet ondersteund" msgid "Framebuffer requires %d bytes" msgstr "Framebuffer benodigd %d bytes" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" "Frequentie moet overeenkomen met bestaande PWMOut bij gebruik van deze timer" @@ -1038,10 +1071,6 @@ msgstr "" msgid "Group already used" msgstr "Groep al gebruikt" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Groep is vol" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1072,15 +1101,15 @@ msgstr "" msgid "I2SOut not available" msgstr "I2SOut is niet beschikbaar" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IO's 0, 2 en 4 ondersteunen geen interne pullup in slaapstand" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IV %d bytes lang zijn" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1097,10 +1126,23 @@ msgstr "Incorrecte buffer grootte" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "De initialisatie is mislukt vanwege een gebrek aan geheugen" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "Invoer duurt te lang" @@ -1157,6 +1199,7 @@ msgstr "Ongeldige %q" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Ongeldige %q pin" @@ -1183,8 +1226,14 @@ msgstr "Ongeldig BSSID" msgid "Invalid DAC pin supplied" msgstr "Ongeldige DAC pin opgegeven" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Ongeldige PWM frequentie" @@ -1202,7 +1251,8 @@ msgstr "Ongeldig argument" msgid "Invalid bits per value" msgstr "Ongeldige bits per waarde" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Ongeldige buffer grootte" @@ -1231,14 +1281,10 @@ msgstr "Ongeldig bestand" msgid "Invalid format chunk size" msgstr "Ongeldig formaat stuk grootte" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Onjuiste frequentie" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Ongeldige frequentie opgegeven" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Ongeldig geheugen adres." @@ -1277,17 +1323,13 @@ msgstr "Ongeldige pin voor rechter kanaal" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Ongeldige pinnen" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Ongeldige pinnen voor PWMOut" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1309,7 +1351,7 @@ msgstr "Ongeldige security_mode" msgid "Invalid size" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1317,10 +1359,6 @@ msgstr "" msgid "Invalid state" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "Ongeldige stem" @@ -1333,14 +1371,11 @@ msgstr "Ongeldig stem aantal" msgid "Invalid wave file" msgstr "Ongeldig wave bestand" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Ongeldig woord/bit lengte" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "Sleutel moet 16, 24, of 32 bytes lang zijn" @@ -1386,14 +1421,6 @@ msgstr "Maximale x waarde indien gespiegeld is %d" msgid "Messages limited to 8 bytes" msgstr "Berichten zijn beperkt tot 8 bytes" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR sprong mislukt. Waarschijnlijk geheugen corruptie." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython fatale fout." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Microfoon opstart vertraging moet in bereik van 0.0 tot 1.0 zijn" @@ -1445,6 +1472,10 @@ msgstr "MISO of MOSI moeten worden gegeven" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Een meervoud van 6 rgb pinnen moet worden gebruikt, niet %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS-fout" @@ -1464,9 +1495,15 @@ msgstr "Geen DAC op de chip" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Geen DMA kanaal gevonden" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1525,6 +1562,14 @@ msgstr "Geen hardware ondersteuning beschikbaar op clk pin" msgid "No hardware support on pin" msgstr "Geen hardware ondersteuning op pin" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Een sleutel was niet gespecificeerd" @@ -1533,18 +1578,6 @@ msgstr "Een sleutel was niet gespecificeerd" msgid "No long integer support" msgstr "Geen lange integer ondersteuning" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "Geen kanalen meer beschikbaar" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "Geen timers meer beschikbaar" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "Geen timers meer beschikbaar op deze pin." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "Geen netwerk met dat SSID gevonden" @@ -1553,6 +1586,12 @@ msgstr "Geen netwerk met dat SSID gevonden" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "Geen pulldown op pin; 1MOhm aangeraden" @@ -1570,13 +1609,18 @@ msgid "No timer available" msgstr "Geen timer beschikbaar" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Nordic Soft Device assertion mislukt." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "Geen geldige IP string" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1607,13 +1651,10 @@ msgid "Odd parity is not supported" msgstr "Oneven pariteit is niet ondersteund" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Alleen 8 of 16 bit mono met " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "Alleen IPv4 adressen worden ondersteund" @@ -1667,10 +1708,19 @@ msgstr "" msgid "Out of memory" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "Geen sockets meer beschikbaar" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Oversample moet een meervoud van 8 zijn." @@ -1692,8 +1742,15 @@ msgstr "" "PWM frequentie is niet schrijfbaar wanneer de variable_frequency False is " "tijdens constructie." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBus nog niet ondersteund" @@ -1729,6 +1786,10 @@ msgstr "Pin heeft geen ADC mogelijkheden" msgid "Pin is input only" msgstr "Pin kan alleen voor invoer gebruikt worden" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "Pin moet hardware interrupts ondersteunen" @@ -1748,6 +1809,14 @@ msgstr "" "gebruikt. Als dit niet kan worden vermeden, geef dan het argument " "allow_inefficient=True aan de constructor" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "En iedere module in het bestandssysteem\n" @@ -1825,6 +1894,10 @@ msgstr "RNG DeInit Fout" msgid "RNG Init Error" msgstr "RNG Init Fout" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1832,6 +1905,7 @@ msgstr "RS485 inversie gespecificeerd terwijl niet in RS485 modus" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "RTC calibratie niet ondersteund door dit board" @@ -1840,7 +1914,7 @@ msgid "RTC is not supported on this board" msgstr "RTC is niet ondersteund door dit board" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS/CTS/RS485 Nog niet ondersteund door dit apparaat" @@ -1897,12 +1971,6 @@ msgstr "Veilige modus wordt uitgevoerd! " msgid "SD card CSD format not supported" msgstr "SD kaart CSD formaat niet ondersteund" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA of SCL hebben een pullup nodig" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1938,14 +2006,6 @@ msgstr "Sample rate is te hoog. Moet minder dan %d zijn" msgid "Scan already in progess. Stop with stop_scan." msgstr "Scan wordt al uitvoerd. Stop met stop_scan." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "Geselecteerde CTS pin niet geldig" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "Geselecteerde RTS pin niet geldig" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1994,6 +2054,14 @@ msgstr "Splitting met sub-captures" msgid "Stack size must be at least 256" msgstr "Stack grootte moet op zijn minst 256 zijn" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Stream mist readinto() of write() methode." @@ -2086,18 +2154,12 @@ msgstr "Tijdstip ligt in het verleden." msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "Time-out is te lang. Maximale time-out lengte is %d seconden" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" -"Timer is gereserveerd voor intern gebruik - wijs PWM pins eerder in het " -"programma toe" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Om te beëindigen, reset het bord zonder " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Teveel kanalen in sample." @@ -2110,8 +2172,8 @@ msgid "Too many displays" msgstr "Teveel beeldschermen" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "Totale data om te schrijven is groter dan outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2137,10 +2199,6 @@ msgstr "UART Init Fout" msgid "UART Re-init error" msgstr "UART Re-init Fout" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "UART schrijf fout" @@ -2167,6 +2225,8 @@ msgstr "UUID waarde is geen str, int, of byte buffer" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Niet in staat buffers voor gesigneerde conversie te alloceren" @@ -2204,7 +2264,7 @@ msgstr "Kan niet naar sleep_memory schrijven." msgid "Unexpected nrfx uuid type" msgstr "Onverwacht mrfx uuid type" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "Niet behandelde ESP TLS fout %d %d %x %d" @@ -2230,8 +2290,8 @@ msgstr "Onbekende veiligheidsfout: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Onbekende soft device fout: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2260,7 +2320,7 @@ msgstr "Niet-ondersteund beeldscherm bus type" msgid "Unsupported format" msgstr "Niet-ondersteunde format" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Niet-ondersteunde operatie" @@ -2286,10 +2346,6 @@ msgstr "Waarde length > max_length" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper-functies ondersteunen momenteel niet meer dan 4 argumenten" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Voltage lees time-out" @@ -2378,11 +2434,6 @@ msgstr "een bytes-achtig object is vereist" msgid "abort() called" msgstr "abort() aangeroepen" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "adres %08x is niet afgestemd op %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adres buiten bereik" @@ -2391,15 +2442,19 @@ msgstr "adres buiten bereik" msgid "addresses is empty" msgstr "adressen zijn leeg" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg is een lege sequentie" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "argsort argument moet een ndarray zijn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "argsort wordt niet geïmplementeerd voor vlakke arrays" @@ -2407,10 +2462,6 @@ msgstr "argsort wordt niet geïmplementeerd voor vlakke arrays" msgid "argument has wrong type" msgstr "argument heeft onjuist type" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "argument moet ndarray zijn" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2420,7 +2471,8 @@ msgstr "argument num/typen komen niet overeen" msgid "argument should be a '%q' not a '%q'" msgstr "argument moet een '%q' zijn en niet een '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "argumenten moeten ndarrays zijn" @@ -2433,11 +2485,11 @@ msgstr "array en indexlengte moeten gelijk zijn" msgid "array/bytes required on right side" msgstr "array/bytes vereist aan de rechterkant" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "verzoek om (arg)min.(arg)max te krijgen van lege reeks" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "poging om argmin/argmax van een lege sequentie te krijgen" @@ -2445,15 +2497,15 @@ msgstr "poging om argmin/argmax van een lege sequentie te krijgen" msgid "attributes not supported yet" msgstr "attributen nog niet ondersteund" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "as is buiten bereik" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "as moet None of een integer zijn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "as te lang" @@ -2478,8 +2530,8 @@ msgid "binary op %q not implemented" msgstr "binaire op %q niet geïmplementeerd" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bits moet 7, 8, of 9 zijn" +msgid "bits must be in range 5 to 9" +msgstr "" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2489,15 +2541,11 @@ msgstr "bits_per_sample moet 8 of 16 zijn" msgid "branch not in range" msgstr "pad (branch) niet binnen bereik" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer moet een byte-achtig object zijn" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2514,7 +2562,7 @@ msgstr "buffer slices moeten van gelijke grootte zijn" msgid "buffer too small" msgstr "buffer te klein" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "buffer te klein voor gevraagde bytes" @@ -2581,6 +2629,10 @@ msgstr "kan niet toewijzen aan expressie" msgid "can't convert %q to %q" msgstr "kan %q niet naar %q converteren" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "kan '%q' object niet omzetten naar %q impliciet" @@ -2589,6 +2641,10 @@ msgstr "kan '%q' object niet omzetten naar %q impliciet" msgid "can't convert to %q" msgstr "kan niet naar %q converteren" +#: py/runtime.c +msgid "can't convert to int" +msgstr "kan niet omzetten naar int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "kan niet omzetten naar str impliciet" @@ -2708,6 +2764,10 @@ msgid "circle can only be registered in one parent" msgstr "" "cirkel kan slechts bij één object van een hoger niveau worden geregistreerd" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2752,19 +2812,19 @@ msgstr "constant moet een integer zijn" msgid "conversion to object" msgstr "conversie naar object" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "convolutie argumenten moeten lineaire arrays zijn" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "convolutie argumenten moeten ndarrays zijn" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "convolutie argumenten mogen niet leeg zijn" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "kon de Vandermonde matrix niet omkeren" @@ -2772,15 +2832,15 @@ msgstr "kon de Vandermonde matrix niet omkeren" msgid "couldn't determine SD card version" msgstr "kon SD kaart versie niet bepalen" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "kruis wordt gedefinieerd voor 1D-arrays van lengte 3" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "data moet itereerbaar zijn" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "data moet van gelijke lengte zijn" @@ -2819,14 +2879,18 @@ msgstr "destination_lengte moest een int groter dan of gelijk zijn aan 0 zijn" msgid "dict update sequence has wrong length" msgstr "dict update sequence heeft de verkeerde lengte" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "diff argument moet een ndarray zijn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "differentiatievolgorde buiten bereik" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2934,7 +2998,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: enkele '}' is niet toegestaan" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "bestand moet een bestand zijn geopend in byte modus" @@ -2942,11 +3006,11 @@ msgstr "bestand moet een bestand zijn geopend in byte modus" msgid "filesystem must provide mount method" msgstr "bestandssysteem moet een mount methode bieden" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "eerste argument moet een aanroepbare (callable) zijn" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "eerste argument moet een functie zijn" @@ -2954,11 +3018,7 @@ msgstr "eerste argument moet een functie zijn" msgid "first argument must be a tuple of ndarrays" msgstr "eerste argument moet een tupel van ndarrays zijn" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "eerst argument moet een iterabel zijn" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "eerst argument moet een ndarray zijn" @@ -2970,7 +3030,7 @@ msgstr "eerste argument voor super() moet een type zijn" msgid "flattening order must be either 'C', or 'F'" msgstr "De afvlakkingsvolgorde moet ofwel \"C\", ofwel \"F\" zijn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "flip argumenten moeten een ndarray zijn" @@ -2991,8 +3051,8 @@ msgid "full" msgstr "vol" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "functie accepteert geen keyword argumenten" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3003,7 +3063,7 @@ msgstr "functie verwachtte op zijn meest %d argumenten, maar kreeg %d" msgid "function got multiple values for argument '%q'" msgstr "functie kreeg meedere waarden voor argument '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "functie heeft hetzelfde teken aan beide uiteinden van het interval" @@ -3047,6 +3107,10 @@ msgstr "generator wordt al uitgevoerd" msgid "generator ignored GeneratorExit" msgstr "generator negeerde GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic moet 2048 bytes lang zijn" @@ -3079,8 +3143,9 @@ msgstr "vulling (padding) is onjuist" msgid "index is out of bounds" msgstr "index is buiten bereik" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "index is buiten bereik" @@ -3092,7 +3157,7 @@ msgstr "indices moeten integers zijn" msgid "indices must be integers, slices, or Boolean lists" msgstr "indices moeten integers, segmenten (slices) of Boolean lijsten zijn" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "oorspronkelijke waarden moeten itereerbaar zijn" @@ -3112,7 +3177,7 @@ msgstr "in- en uitvoervormen zijn niet compatibel" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "invoer array lengte moet een macht van 2 zijn" @@ -3120,15 +3185,15 @@ msgstr "invoer array lengte moet een macht van 2 zijn" msgid "input arrays are not compatible" msgstr "input arrays zijn niet compatibel" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "invoerdata moet itereerbaar zijn" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "invoermatrix is asymmetrisch" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "invoermatrix is singulier" @@ -3144,23 +3209,23 @@ msgstr "invoer moet een tensor van rang 2 zijn" msgid "input must be an ndarray" msgstr "invoer moet een ndarray zijn" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "invoer moet eendimensionaal zijn" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "invoer moet een vierkante matrix zijn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "invoer moet een tuple, lijst, bereik of ndarray zijn" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "invoervectors moeten van gelijke lengte zijn" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "invoer is niet itereerbaar" @@ -3172,7 +3237,7 @@ msgstr "int() argument 2 moet >=2 en <= 36 zijn" msgid "integer required" msgstr "integer vereist" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "interp is gedefinieerd voor eendimensionale arrays van gelijke lengte" @@ -3185,14 +3250,33 @@ msgstr "interval moet binnen bereik %s-%s vallen" msgid "invalid arguments" msgstr "ongeldige argumenten" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "ongeldig certificaat" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "ongeldige dupterm index" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "ongeldig formaat" @@ -3234,10 +3318,6 @@ msgstr "ongeldige syntax voor integer met grondtal %d" msgid "invalid syntax for number" msgstr "ongeldige syntax voor nummer" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io moet rtc io zijn" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() argument 1 moet een klasse zijn" @@ -3246,11 +3326,7 @@ msgstr "issubclass() argument 1 moet een klasse zijn" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass() argument 2 moet een klasse of tuple van klassen zijn" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "itereerbare objecten hebben niet dezelfde lengte" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "itereerbare objecten convergeren niet" @@ -3321,11 +3397,7 @@ msgstr "map buffer te klein" msgid "math domain error" msgstr "fout in het wiskundig domein (math domain error)" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "matrix afmetingen komen niet overeen" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "matrix is niet positief-definiet" @@ -3347,15 +3419,15 @@ msgstr "maximaal aantal dimensies is 4" msgid "maximum recursion depth exceeded" msgstr "maximale recursiediepte overschreden" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "maxiter moet groter dan 0 zijn" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "maxiter moet groter dan 0 zijn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3368,11 +3440,15 @@ msgstr "geheugentoewijzing mislukt, %u bytes worden toegewezen" msgid "memory allocation failed, heap is locked" msgstr "geheugentoewijzing mislukt, heap is vergrendeld" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "module niet gevonden" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "meer vrijheidsgraden dan datapunten" @@ -3417,6 +3493,10 @@ msgstr "natuurlijke opbrengst (native yield)" msgid "need more than %d values to unpack" msgstr "Om uit te pakken zijn meer dan %d waarden vereist" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negatieve macht terwijl er geen ondersteuning is voor float" @@ -3490,10 +3570,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "norm is gedefinieerd voor 1D en 2D arrays" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "geen 128-bit UUID" @@ -3562,7 +3638,7 @@ msgstr "object met buffer protocol vereist" msgid "odd-length string" msgstr "string met oneven lengte" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "compensatie is te groot" @@ -3591,8 +3667,8 @@ msgstr "alleen sample_rate=16000 wordt ondersteund" msgid "only slices with step=1 (aka None) are supported" msgstr "alleen segmenten met step=1 (ook wel None) worden ondersteund" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "operands konden niet samen verzonden worden" @@ -3600,7 +3676,7 @@ msgstr "operands konden niet samen verzonden worden" msgid "operation is implemented for 1D Boolean arrays only" msgstr "operatie is alleen geïmplementeerd voor 1D Booleaanse arrays" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "bewerking is voor ndarrays niet geïmplementeerd" @@ -3617,11 +3693,19 @@ msgstr "ord verwacht een teken (char)" msgid "ord() expected a character, but string of length %d found" msgstr "ord() verwacht een teken (char) maar vond een string van lengte %d" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "buiten bereik van bron" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "buiten bereik van doel" @@ -3642,10 +3726,6 @@ msgstr "palette moet 32 bytes lang zijn" msgid "palette_index should be an int" msgstr "palette_index moet een int zijn" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parameter annotatie moet een identifier zijn" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parameters moeten registers zijn in de volgorde a2 tot a5" @@ -3654,7 +3734,7 @@ msgstr "parameters moeten registers zijn in de volgorde a2 tot a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "parameters moeten registers zijn in de volgorde r0 tot r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "pixel coördinaten buiten bereik" @@ -3678,11 +3758,16 @@ msgstr "pop van een lege PulseIn" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "pop van een lege %q" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "derde argument van pow() mag geen 0 zijn" @@ -3693,12 +3778,17 @@ msgstr "pow() met 3 argumenten vereist integers" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3706,6 +3796,7 @@ msgstr "pow() met 3 argumenten vereist integers" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "druk bootknop in bij opstarten.\n" @@ -3717,6 +3808,14 @@ msgstr "druk bootknop in bij opstarten.\n" msgid "pressing both buttons at start up.\n" msgstr "druk beide knoppen in bij opstarten.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3733,7 +3832,7 @@ msgstr "wachtrij overloop" msgid "raw f-strings are not implemented" msgstr "ruwe f-strings zijn niet geïmplementeerd" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "reëel en imaginair deel moeten gelijke lengte hebben" @@ -3768,7 +3867,7 @@ msgstr "rgb_pins[%d] is hetzelfde als een andere pintoewijzing" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins[%d] bevindt zich niet op dezelfde poort als klok" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "roll argument moet een ndarray zijn" @@ -3785,6 +3884,7 @@ msgstr "" "'B' zijn" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "bemonsteringssnelheid buiten bereik" @@ -3816,7 +3916,7 @@ msgstr "teken niet toegestaan bij integer formaatspecificatie 'c'" msgid "single '}' encountered in format string" msgstr "enkele '}' aangetroffen in formaat tekenreeks (string)" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "omvang is alleen voor ndarrays gedefinieerd" @@ -3840,23 +3940,23 @@ msgstr "small int overloop" msgid "soft reboot\n" msgstr "zachte herstart\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "sorteerargument moet een ndarray zijn" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "sos array moet vorm (n_section, 6) hebben" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "sos[:, 3] moeten allemaal 1 zijn" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "sosfilt vereist itereerbare argumenten" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "bronpalet te groot" @@ -3966,7 +4066,7 @@ msgstr "tobytes kunnen alleen ingeroepen worden voor gesloten arrays" msgid "too many arguments provided with the given format" msgstr "te veel argumenten opgegeven bij dit formaat" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3979,18 +4079,14 @@ msgstr "te veel indices" msgid "too many values to unpack (expected %d)" msgstr "te veel waarden om uit te pakken (%d verwacht)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "trapz is gedefinieerd voor eendimensionale arrays van gelijke lengte" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "triggerniveau moet 0 of 1 zijn" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tuple of lijst heeft onjuiste lengte" @@ -4072,7 +4168,7 @@ msgstr "onbekende formaatcode '%c' voor object van type '%q'" msgid "unknown type" msgstr "onbekend type" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "onbekend type '%q'" @@ -4125,14 +4221,6 @@ msgstr "waarde moet in %d byte(s) passen" msgid "value_count must be > 0" msgstr "value_count moet groter dan 0 zijn" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "vectoren moeten van gelijke lengte zijn" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "conflict bij ontwaken" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "watchdog niet geïnitialiseerd" @@ -4141,6 +4229,11 @@ msgstr "watchdog niet geïnitialiseerd" msgid "watchdog timeout must be greater than 0" msgstr "watchdog time-out moet groter zijn dan 0" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "breedte moet groter dan nul zijn" @@ -4153,7 +4246,7 @@ msgstr "" msgid "window must be <= interval" msgstr "window moet <= interval zijn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "foute index voor as" @@ -4161,7 +4254,8 @@ msgstr "foute index voor as" msgid "wrong axis specified" msgstr "onjuiste as gespecificeerd" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "onjuist invoertype" @@ -4177,7 +4271,7 @@ msgstr "verkeerd aantal waarden om uit te pakken" msgid "wrong operand type" msgstr "verkeerd operandtype" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "onjuist uitvoer type" @@ -4201,18 +4295,124 @@ msgstr "y-waarde buiten bereik" msgid "zero step" msgstr "nul-stap" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "zi moet een ndarray zijn" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "zi moet van type float zijn" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "zi moet vorm (n_section, 2) hebben" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper-functies ondersteunen momenteel niet meer dan 4 argumenten" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "adres %08x is niet afgestemd op %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "functie accepteert geen keyword argumenten" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parameter annotatie moet een identifier zijn" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Totale data om te schrijven is groter dan outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IO's 0, 2 en 4 ondersteunen geen interne pullup in slaapstand" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer moet een byte-achtig object zijn" + +#~ msgid "io must be rtc io" +#~ msgstr "io moet rtc io zijn" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "triggerniveau moet 0 of 1 zijn" + +#~ msgid "wakeup conflict" +#~ msgstr "conflict bij ontwaken" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "heap allocatie geprobeerd terwijl MicroPython VM niet draait." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR sprong mislukt. Waarschijnlijk geheugen corruptie." + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython fatale fout." + +#~ msgid "argument must be ndarray" +#~ msgstr "argument moet ndarray zijn" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "matrix afmetingen komen niet overeen" + +#~ msgid "norm is defined for 1D and 2D arrays" +#~ msgstr "norm is gedefinieerd voor 1D en 2D arrays" + +#~ msgid "vectors must have same lengths" +#~ msgstr "vectoren moeten van gelijke lengte zijn" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Nordic Soft Device assertion mislukt." + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Onbekende soft device fout: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "eerst argument moet een iterabel zijn" + +#~ msgid "iterables are not of the same length" +#~ msgstr "itereerbare objecten hebben niet dezelfde lengte" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Geselecteerde CTS pin niet geldig" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Geselecteerde RTS pin niet geldig" + +#~ msgid "Could not initialize channel" +#~ msgstr "Kan kanaal niet initialiseren" + +#~ msgid "Could not initialize timer" +#~ msgstr "Kan timer niet initialiseren" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Ongeldige frequentie opgegeven" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Ongeldige pinnen voor PWMOut" + +#~ msgid "No more channels available" +#~ msgstr "Geen kanalen meer beschikbaar" + +#~ msgid "No more timers available" +#~ msgstr "Geen timers meer beschikbaar" + +#~ msgid "No more timers available on this pin." +#~ msgstr "Geen timers meer beschikbaar op deze pin." + +#~ msgid "" +#~ "Timer was reserved for internal use - declare PWM pins earlier in the " +#~ "program" +#~ msgstr "" +#~ "Timer is gereserveerd voor intern gebruik - wijs PWM pins eerder in het " +#~ "programma toe" + +#~ msgid "Group full" +#~ msgstr "Groep is vol" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bits moet 7, 8, of 9 zijn" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA of SCL hebben een pullup nodig" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "%d adres pins en %d RGB pins geven een hoogte van %d aan, niet %d" @@ -4389,9 +4589,6 @@ msgstr "zi moet vorm (n_section, 2) hebben" #~ msgid "can't convert to float" #~ msgstr "kan niet omzetten naar float" -#~ msgid "can't convert to int" -#~ msgstr "kan niet omzetten naar int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "object '%s' is geen tuple of lijst" diff --git a/locale/pl.po b/locale/pl.po index e9a794cac8b86..1fbc6e4e34a25 100644 --- a/locale/pl.po +++ b/locale/pl.po @@ -7,7 +7,7 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-01-27 01:31+0000\n" +"PO-Revision-Date: 2021-02-10 21:50+0000\n" "Last-Translator: Maciej Stankiewicz \n" "Language-Team: pl\n" "Language: pl\n" @@ -78,6 +78,7 @@ msgstr "%q w użyciu" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -107,6 +108,7 @@ msgstr "%q musi być >= 1" msgid "%q must be a tuple of length 2" msgstr "%q musi być krotką o długości 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q poza zakresem" @@ -337,9 +339,14 @@ msgid "All SPI peripherals are in use" msgstr "Wszystkie peryferia SPI w użyciu" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Wszystkie peryferia UART w użyciu" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Wszystkie kanały zdarzeń w użyciu" @@ -368,6 +375,7 @@ msgstr "Wszystkie timery tej nóżki w użyciu" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Wszystkie timery w użyciu" @@ -408,6 +416,10 @@ msgstr "AnalogOut ma 16 bitów. Wartość musi być mniejsza od 65536." msgid "AnalogOut not supported on given pin" msgstr "AnalogOut niewspierany na tej nóżce" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -431,8 +443,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Próba przydzielenia %d bloków" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Próba przydziału sterty, gdy MicroPython VM nie działa." +msgid "Attempted heap allocation when VM not running." +msgstr "" #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -459,6 +471,10 @@ msgstr "" msgid "Below minimum frame rate" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Zegar bitowy i wybór słowa muszą współdzielić jednostkę zegara" @@ -500,6 +516,10 @@ msgstr "Jasność nie jest regulowana" msgid "Buffer + offset too small %d %d %d" msgstr "Bufor + przesunięcie za małe %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -516,6 +536,7 @@ msgid "Buffer is too small" msgstr "Bufor jest za mały" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "Długość %d bufora jest za duża. Musi być mniejsza niż %d" @@ -545,6 +566,7 @@ msgstr "Bufor za krótki o %d bajtów" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Nóżka magistrali %d jest w użyciu" @@ -636,6 +658,10 @@ msgstr "Nie można przemontować '/' gdy USB działa." msgid "Cannot reset into bootloader because no bootloader is present." msgstr "Nie można zrestartować -- nie ma bootloadera." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Nie można ustawić wartości w trybie wejścia." @@ -657,7 +683,7 @@ msgstr "Nie można przesyłać bez nóżek MOSI i MISO." msgid "Cannot unambiguously get sizeof scalar" msgstr "Wielkość skalara jest niejednoznaczna" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "Nie można zmieniać częstotliwości timera, który jest już używany" @@ -743,14 +769,6 @@ msgstr "Nie można zainicjować SDCard" msgid "Could not initialize UART" msgstr "Ustawienie UART nie powiodło się" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Nie można zainicjować kanału" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Nie można zainicjować timera" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Nie można ponownie zainicjować kanału" @@ -771,7 +789,7 @@ msgstr "" msgid "Could not set address" msgstr "Nie można ustawić adresu" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "Nie można uruchomić PWM" @@ -872,11 +890,16 @@ msgstr "" msgid "EXTINT channel already in use" msgstr "Kanał EXTINT w użyciu" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "" + #: extmod/modure.c msgid "Error in regex" msgstr "Błąd w regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "" @@ -927,15 +950,15 @@ msgstr "Oczekiwano krotkę długości %d, otrzymano %d" msgid "Extended advertisements with scan response not supported." msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "" @@ -949,6 +972,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Nie udało się uzyskać blokady, błąd 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Nie udała się alokacja bufora RX" @@ -957,6 +981,7 @@ msgstr "Nie udała się alokacja bufora RX" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -970,6 +995,10 @@ msgstr "" msgid "Failed to allocate wifi scan memory" msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Nie udało się połączyć: błąd wewnętrzny" @@ -995,6 +1024,10 @@ msgstr "Nie udało się zwolnić blokady, błąd 0x%04x" msgid "Failed to write internal flash." msgstr "Nie udało się zapisać wewnętrznej pamięci flash." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "" + #: py/moduerrno.c msgid "File exists" msgstr "Plik istnieje" @@ -1018,7 +1051,7 @@ msgstr "Nie wspierany format" msgid "Framebuffer requires %d bytes" msgstr "Bufor ramki wymaga %d bajtów" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" @@ -1037,10 +1070,6 @@ msgstr "" msgid "Group already used" msgstr "Grupa już używana" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Grupa pełna" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1071,15 +1100,15 @@ msgstr "" msgid "I2SOut not available" msgstr "I2SOut niedostępne" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IV musi mieć długość %d bajtów" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1096,10 +1125,23 @@ msgstr "Niewłaściwa wielkość bufora" msgid "Init program size invalid" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "Inicjalizacja nie powiodła się z powodu braku pamięci" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "" @@ -1156,6 +1198,7 @@ msgstr "Nieprawidłowe %q" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Zła nóżka %q" @@ -1182,8 +1225,14 @@ msgstr "" msgid "Invalid DAC pin supplied" msgstr "" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Zła częstotliwość PWM" @@ -1201,7 +1250,8 @@ msgstr "Zły argument" msgid "Invalid bits per value" msgstr "Zła liczba bitów wartości" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Zła wielkość bufora" @@ -1230,14 +1280,10 @@ msgstr "Zły plik" msgid "Invalid format chunk size" msgstr "Zła wielkość fragmentu formatu" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Nieprawidłowa częstotliwość" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Podano nieprawidłową częstotliwość" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Nieprawidłowy dostęp do pamięci." @@ -1276,17 +1322,13 @@ msgstr "Zła nóżka dla prawego kanału" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Złe nóżki" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Nieprawidłowe piny dla PWMOut" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1308,7 +1350,7 @@ msgstr "Nieprawidłowy security_mode" msgid "Invalid size" msgstr "Nieprawidłowy rozmiar" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "" @@ -1316,10 +1358,6 @@ msgstr "" msgid "Invalid state" msgstr "Nieprawidłowy stan" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "" @@ -1332,14 +1370,11 @@ msgstr "Zła liczba głosów" msgid "Invalid wave file" msgstr "Zły plik wave" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Niepoprawna długość słowa/bitu" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "Klucz musi mieć długość 16, 24 lub 32 bajtów" @@ -1385,15 +1420,6 @@ msgstr "Największa wartość x przy odwróceniu to %d" msgid "Messages limited to 8 bytes" msgstr "Wiadomości ograniczone do 8 bajtów" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "" -"Skok MicroRython NLR nie powiódł się. Prawdopodobne uszkodzenie pamięci." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Błąd krytyczny MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Opóźnienie włączenia mikrofonu musi być w zakresie od 0.0 do 1.0" @@ -1445,6 +1471,10 @@ msgstr "Należy podać pin MISO lub MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "" + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "" @@ -1464,9 +1494,15 @@ msgstr "Brak DAC" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Nie znaleziono kanału DMA" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1525,6 +1561,14 @@ msgstr "" msgid "No hardware support on pin" msgstr "Brak sprzętowej obsługi na nóżce" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Nie określono klucza" @@ -1533,18 +1577,6 @@ msgstr "Nie określono klucza" msgid "No long integer support" msgstr "" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "Brak dostępnych kanałów" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "" - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "" @@ -1553,6 +1585,12 @@ msgstr "" msgid "No out in program" msgstr "" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "" @@ -1570,13 +1608,18 @@ msgid "No timer available" msgstr "Brak dostępnego timera" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." +msgid "Nordic system firmware failure assertion." +msgstr "" + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1605,13 +1648,10 @@ msgid "Odd parity is not supported" msgstr "Nieparzysta parzystość nie jest wspierana" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Tylko 8 lub 16 bitów mono z " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "" @@ -1661,10 +1701,19 @@ msgstr "" msgid "Out of memory" msgstr "Brak pamięci" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Nadpróbkowanie musi być wielokrotnością 8." @@ -1683,8 +1732,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "Nie można zmienić częstotliwości PWM gdy variable_frequency=False." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBus nie jest jeszcze obsługiwany" @@ -1720,6 +1776,10 @@ msgstr "Nóżka nie obsługuje ADC" msgid "Pin is input only" msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "Pin musi obsługiwać przerwania sprzętowe" @@ -1736,6 +1796,14 @@ msgid "" "constructor" msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Oraz moduły w systemie plików\n" @@ -1807,6 +1875,10 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1814,6 +1886,7 @@ msgstr "" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "Brak obsługi kalibracji RTC" @@ -1822,7 +1895,7 @@ msgid "RTC is not supported on this board" msgstr "Brak obsługi RTC" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "" @@ -1879,12 +1952,6 @@ msgstr "" msgid "SD card CSD format not supported" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA lub SCL wymagają podciągnięcia" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1920,14 +1987,6 @@ msgstr "Zbyt wysoka częstotliwość próbkowania. Musi być mniejsza niż %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "Skanuj już w toku. Zatrzymaj za pomocą stop_scan." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "Wybrany pin CTS jest nieprawidłowy" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "Wybrany pin RTS jest nieprawidłowy" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1976,6 +2035,14 @@ msgstr "Podział z podgrupami" msgid "Stack size must be at least 256" msgstr "Stos musi mieć co najmniej 256 bajtów" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Strumień nie ma metod readinto() lub write()." @@ -2060,16 +2127,12 @@ msgstr "" msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "By wyjść, proszę zresetować płytkę bez " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Zbyt wiele kanałów." @@ -2082,7 +2145,7 @@ msgid "Too many displays" msgstr "Zbyt wiele wyświetlaczy" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" +msgid "Total data to write is larger than %q" msgstr "" #: py/obj.c @@ -2109,10 +2172,6 @@ msgstr "" msgid "UART Re-init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "Błąd zapisu UART" @@ -2139,6 +2198,8 @@ msgstr "UUID nie jest typu str, int lub bytes" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Nie udała się alokacja buforów do konwersji ze znakiem" @@ -2176,7 +2237,7 @@ msgstr "" msgid "Unexpected nrfx uuid type" msgstr "Nieoczekiwany typ nrfx uuid" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "" @@ -2202,7 +2263,7 @@ msgstr "" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" +msgid "Unknown system firmware error: %04x" msgstr "" #: shared-bindings/_pixelbuf/PixelBuf.c @@ -2230,7 +2291,7 @@ msgstr "Zły typ magistrali wyświetlaczy" msgid "Unsupported format" msgstr "Zły format" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Zła operacja" @@ -2256,10 +2317,6 @@ msgstr "" msgid "Version was invalid" msgstr "" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Funkcje Viper nie obsługują obecnie więcej niż 4 argumentów" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "" @@ -2345,11 +2402,6 @@ msgstr "wymagany obiekt typu bytes" msgid "abort() called" msgstr "Wywołano abort()" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "adres %08x nie jest wyrównany do %d bajtów" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adres poza zakresem" @@ -2358,15 +2410,19 @@ msgstr "adres poza zakresem" msgid "addresses is empty" msgstr "adres jest pusty" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg jest puste" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "" @@ -2374,10 +2430,6 @@ msgstr "" msgid "argument has wrong type" msgstr "argument ma zły typ" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2387,7 +2439,8 @@ msgstr "zła liczba lub typ argumentów" msgid "argument should be a '%q' not a '%q'" msgstr "argument powinien być '%q' a nie '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "" @@ -2400,11 +2453,11 @@ msgstr "" msgid "array/bytes required on right side" msgstr "tablica/bytes wymagane po prawej stronie" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" @@ -2412,15 +2465,15 @@ msgstr "" msgid "attributes not supported yet" msgstr "atrybuty nie są jeszcze obsługiwane" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "" @@ -2445,8 +2498,8 @@ msgid "binary op %q not implemented" msgstr "brak dwu-argumentowego operatora %q" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bits musi być 7, 8 lub 9" +msgid "bits must be in range 5 to 9" +msgstr "" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2456,15 +2509,11 @@ msgstr "bits_per_sample musi być 8 lub 16" msgid "branch not in range" msgstr "skok poza zakres" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "bufor mysi być typu bytes" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "" @@ -2481,7 +2530,7 @@ msgstr "fragmenty bufora muszą mieć tę samą długość" msgid "buffer too small" msgstr "zbyt mały bufor" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "" @@ -2547,6 +2596,10 @@ msgstr "przypisanie do wyrażenia" msgid "can't convert %q to %q" msgstr "nie można dokonać konwersji %q na %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "nie można automatycznie skonwertować '%q' do '%q'" @@ -2555,6 +2608,10 @@ msgstr "nie można automatycznie skonwertować '%q' do '%q'" msgid "can't convert to %q" msgstr "" +#: py/runtime.c +msgid "can't convert to int" +msgstr "nie można skonwertować do int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "nie można automatycznie skonwertować do str" @@ -2673,6 +2730,10 @@ msgstr "argument chr() poza zakresem range(256)" msgid "circle can only be registered in one parent" msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "" @@ -2717,19 +2778,19 @@ msgstr "stała musi być liczbą całkowitą" msgid "conversion to object" msgstr "konwersja do obiektu" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "" @@ -2737,15 +2798,15 @@ msgstr "" msgid "couldn't determine SD card version" msgstr "nie można określić wersji karty SD" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "" @@ -2783,14 +2844,18 @@ msgstr "destination_length musi być nieujemną liczbą całkowitą" msgid "dict update sequence has wrong length" msgstr "sekwencja ma złą długość" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2898,7 +2963,7 @@ msgid "f-string: single '}' is not allowed" msgstr "" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "file musi być otwarte w trybie bajtowym" @@ -2906,11 +2971,11 @@ msgstr "file musi być otwarte w trybie bajtowym" msgid "filesystem must provide mount method" msgstr "system plików musi mieć metodę mount" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "pierwszy argument musi być funkcją" @@ -2918,11 +2983,7 @@ msgstr "pierwszy argument musi być funkcją" msgid "first argument must be a tuple of ndarrays" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "pierwszy argument musi być iterowalny" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "" @@ -2934,7 +2995,7 @@ msgstr "pierwszy argument super() musi być typem" msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "" @@ -2955,8 +3016,8 @@ msgid "full" msgstr "pełny" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "funkcja nie bierze argumentów nazwanych" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -2967,7 +3028,7 @@ msgstr "funkcja bierze najwyżej %d argumentów, jest %d" msgid "function got multiple values for argument '%q'" msgstr "funkcja dostała wiele wartości dla argumentu '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "" @@ -3010,6 +3071,10 @@ msgstr "generator już się wykonuje" msgid "generator ignored GeneratorExit" msgstr "generator zignorował GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic musi mieć 2048 bajtów długości" @@ -3042,8 +3107,9 @@ msgstr "złe wypełnienie" msgid "index is out of bounds" msgstr "indeks jest poza zakresem" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "indeks poza zakresem" @@ -3055,7 +3121,7 @@ msgstr "indeksy muszą być całkowite" msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "wartości początkowe muszą być iterowalne" @@ -3075,7 +3141,7 @@ msgstr "" msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "długość tablicy wejściowej musi być potęgą 2" @@ -3083,15 +3149,15 @@ msgstr "długość tablicy wejściowej musi być potęgą 2" msgid "input arrays are not compatible" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "" @@ -3107,23 +3173,23 @@ msgstr "" msgid "input must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "wejście musi być macierzą kwadratową" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "wektory wejściowe muszą być równej długości" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "" @@ -3135,7 +3201,7 @@ msgstr "argument 2 do int() busi być pomiędzy 2 a 36" msgid "integer required" msgstr "wymagana liczba całkowita" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "" @@ -3148,14 +3214,33 @@ msgstr "interwał musi mieścić się w zakresie %s-%s" msgid "invalid arguments" msgstr "złe arguemnty" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "zły ceryfikat" +#: py/compile.c +msgid "invalid decorator" +msgstr "" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "zły indeks dupterm" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "" + #: extmod/modframebuf.c msgid "invalid format" msgstr "zły format" @@ -3197,10 +3282,6 @@ msgstr "zła składnia dla liczby całkowitej w bazie %d" msgid "invalid syntax for number" msgstr "zła składnia dla liczby" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "argument 1 dla issubclass() musi być klasą" @@ -3209,11 +3290,7 @@ msgstr "argument 1 dla issubclass() musi być klasą" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "argument 2 dla issubclass() musi być klasą lub krotką klas" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "" @@ -3281,11 +3358,7 @@ msgstr "bufor mapy zbyt mały" msgid "math domain error" msgstr "błąd domeny" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "" @@ -3307,15 +3380,15 @@ msgstr "" msgid "maximum recursion depth exceeded" msgstr "przekroczono dozwoloną głębokość rekurencji" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "" @@ -3328,11 +3401,15 @@ msgstr "alokacja pamięci nie powiodła się, alokowano %u bajtów" msgid "memory allocation failed, heap is locked" msgstr "alokacja pamięci nie powiodła się, sterta zablokowana" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "" + #: py/builtinimport.c msgid "module not found" msgstr "brak modułu" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "" @@ -3377,6 +3454,10 @@ msgstr "natywny yield" msgid "need more than %d values to unpack" msgstr "potrzeba więcej niż %d do rozpakowania" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "ujemna potęga, ale brak obsługi liczb zmiennoprzecinkowych" @@ -3450,10 +3531,6 @@ msgstr "" msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "to nie jest 128-bitowy UUID" @@ -3522,7 +3599,7 @@ msgstr "wymagany obiekt z protokołem buforu" msgid "odd-length string" msgstr "łańcuch o nieparzystej długości" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "" @@ -3551,8 +3628,8 @@ msgstr "obsługiwane jest tylko sample_rate=16000" msgid "only slices with step=1 (aka None) are supported" msgstr "tylko fragmenty ze step=1 (lub None) są wspierane" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "operandy nie mogły być rozgłaszane razem" @@ -3560,7 +3637,7 @@ msgstr "operandy nie mogły być rozgłaszane razem" msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "" @@ -3577,11 +3654,19 @@ msgstr "ord oczekuje znaku" msgid "ord() expected a character, but string of length %d found" msgstr "ord() oczekuje znaku, a jest łańcuch od długości %d" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "" @@ -3602,10 +3687,6 @@ msgstr "paleta musi mieć 32 bajty długości" msgid "palette_index should be an int" msgstr "palette_index powinien być całkowity" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "anotacja parametru musi być identyfikatorem" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parametry muszą być rejestrami w kolejności a2 do a5" @@ -3614,7 +3695,7 @@ msgstr "parametry muszą być rejestrami w kolejności a2 do a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "parametry muszą być rejestrami w kolejności r0 do r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "współrzędne piksela poza zakresem" @@ -3638,11 +3719,16 @@ msgstr "pop z pustego PulseIn" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "trzeci argument pow() nie może być 0" @@ -3653,12 +3739,17 @@ msgstr "trzyargumentowe pow() wymaga liczb całkowitych" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3666,6 +3757,7 @@ msgstr "trzyargumentowe pow() wymaga liczb całkowitych" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "" @@ -3677,6 +3769,14 @@ msgstr "" msgid "pressing both buttons at start up.\n" msgstr "" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "" @@ -3693,7 +3793,7 @@ msgstr "przepełnienie kolejki" msgid "raw f-strings are not implemented" msgstr "" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "rzeczywiste i urojone części muszą mieć jednakową długość" @@ -3728,7 +3828,7 @@ msgstr "" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "" @@ -3744,6 +3844,7 @@ msgstr "" "bufor sample_source musi być bytearray lub tablicą typu 'h', 'H', 'b' lub 'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "częstotliwość próbkowania poza zakresem" @@ -3775,7 +3876,7 @@ msgstr "znak jest niedopuszczalny w specyfikacji 'c'" msgid "single '}' encountered in format string" msgstr "pojedynczy '}' w specyfikacji formatu" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "" @@ -3799,23 +3900,23 @@ msgstr "przepełnienie small int" msgid "soft reboot\n" msgstr "programowy reset\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "argument sort musi być ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "źródłowa paleta jest zbyt duża" @@ -3925,7 +4026,7 @@ msgstr "" msgid "too many arguments provided with the given format" msgstr "zbyt wiele argumentów podanych dla tego formatu" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "" @@ -3938,18 +4039,14 @@ msgstr "zbyt wiele indeksów" msgid "too many values to unpack (expected %d)" msgstr "zbyt wiele wartości do rozpakowania (oczekiwano %d)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "krotka/lista ma złą długość" @@ -4031,7 +4128,7 @@ msgstr "" msgid "unknown type" msgstr "zły typ" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "zły typ '%q'" @@ -4084,14 +4181,6 @@ msgstr "wartość musi mieścić się w %d bajtach" msgid "value_count must be > 0" msgstr "value_count musi być > 0" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "wektory muszą mieć identyczną długość" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "" @@ -4100,9 +4189,14 @@ msgstr "" msgid "watchdog timeout must be greater than 0" msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" -msgstr "" +msgstr "szerokość musi być większa niż zero" #: ports/esp32s2/common-hal/wifi/Radio.c msgid "wifi is not enabled" @@ -4112,7 +4206,7 @@ msgstr "" msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "" @@ -4120,9 +4214,10 @@ msgstr "" msgid "wrong axis specified" msgstr "" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" -msgstr "" +msgstr "nieprawidłowy typ wejścia" #: extmod/ulab/code/ulab_create.c py/objstr.c msgid "wrong number of arguments" @@ -4136,9 +4231,9 @@ msgstr "zła liczba wartości do rozpakowania" msgid "wrong operand type" msgstr "zły typ operandu" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" -msgstr "" +msgstr "nieprawidłowy typ wyjścia" #: shared-module/displayio/Shape.c msgid "x value out of bounds" @@ -4160,18 +4255,79 @@ msgstr "y poza zakresem" msgid "zero step" msgstr "zerowy krok" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Funkcje Viper nie obsługują obecnie więcej niż 4 argumentów" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "adres %08x nie jest wyrównany do %d bajtów" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "funkcja nie bierze argumentów nazwanych" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "anotacja parametru musi być identyfikatorem" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "bufor mysi być typu bytes" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Próba przydziału sterty, gdy MicroPython VM nie działa." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "" +#~ "Skok MicroRython NLR nie powiódł się. Prawdopodobne uszkodzenie pamięci." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Błąd krytyczny MicroPython." + +#~ msgid "vectors must have same lengths" +#~ msgstr "wektory muszą mieć identyczną długość" + +#~ msgid "first argument must be an iterable" +#~ msgstr "pierwszy argument musi być iterowalny" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Wybrany pin CTS jest nieprawidłowy" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Wybrany pin RTS jest nieprawidłowy" + +#~ msgid "Could not initialize channel" +#~ msgstr "Nie można zainicjować kanału" + +#~ msgid "Could not initialize timer" +#~ msgstr "Nie można zainicjować timera" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Podano nieprawidłową częstotliwość" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Nieprawidłowe piny dla PWMOut" + +#~ msgid "No more channels available" +#~ msgstr "Brak dostępnych kanałów" + +#~ msgid "Group full" +#~ msgstr "Grupa pełna" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bits musi być 7, 8 lub 9" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA lub SCL wymagają podciągnięcia" + #~ msgid "tuple index out of range" #~ msgstr "indeks krotki poza zakresem" @@ -4264,9 +4420,6 @@ msgstr "" #~ msgid "can't convert to float" #~ msgstr "nie można skonwertować do float" -#~ msgid "can't convert to int" -#~ msgstr "nie można skonwertować do int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "obiekt '%s' nie jest krotką ani listą" diff --git a/locale/pt_BR.po b/locale/pt_BR.po index 2b9f9afa2eacb..e3a9e6675ea11 100644 --- a/locale/pt_BR.po +++ b/locale/pt_BR.po @@ -6,7 +6,7 @@ msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-02-01 17:50+0000\n" +"PO-Revision-Date: 2021-04-22 17:16+0000\n" "Last-Translator: Wellington Terumi Uemura \n" "Language-Team: \n" "Language: pt_BR\n" @@ -14,7 +14,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n > 1;\n" -"X-Generator: Weblate 4.5-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -82,6 +82,7 @@ msgstr "%q em uso" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -111,6 +112,7 @@ msgstr "%q deve ser >= 1" msgid "%q must be a tuple of length 2" msgstr "%q deve ser uma tupla de comprimento 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q fora do alcance" @@ -345,9 +347,14 @@ msgid "All SPI peripherals are in use" msgstr "Todos os periféricos SPI estão em uso" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Todos os periféricos UART estão em uso" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "Todos os canais estão em uso" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Todos os canais de eventos em uso" @@ -376,6 +383,7 @@ msgstr "Todos os temporizadores para este pino estão em uso" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Todos os temporizadores em uso" @@ -416,6 +424,10 @@ msgstr "O AnalogOut é de apenas 16 bits. O valor deve ser menor que 65536." msgid "AnalogOut not supported on given pin" msgstr "Saída analógica não suportada no pino fornecido" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "Um outro PWMAudioOut já está ativo" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -439,10 +451,9 @@ msgid "Attempt to allocate %d blocks" msgstr "Tentativa de alocar %d blocos" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." +msgid "Attempted heap allocation when VM not running." msgstr "" -"A tentativa da área de alocação dinâmica de variáveis (heap) quando o " -"MicroPython VM não está em execução." +"Tentativa de alocação das pilhas quando o VM não estiver em funcionamento." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -469,6 +480,10 @@ msgstr "O Baudrate não é suportado pelo periférico" msgid "Below minimum frame rate" msgstr "Abaixo da taxa mínima de quadros" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "O Bit clock e o word select devem ser pinos sequenciais" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "" @@ -512,6 +527,10 @@ msgstr "Brilho não ajustável" msgid "Buffer + offset too small %d %d %d" msgstr "O buffer + desvio é muito pequeno %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Os elementos do buffer devem ter 4 bytes de comprimento ou menos" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -528,6 +547,7 @@ msgid "Buffer is too small" msgstr "O buffer é muito pequeno" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "O tamanho do buffer %d é muito grande. Deve ser menor que %d" @@ -557,6 +577,7 @@ msgstr "O buffer é muito curto em %d bytes" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "O pino bus %d já está em uso" @@ -654,6 +675,10 @@ msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" "Não é possível redefinir para o bootloader porque o mesmo não está presente." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "Não foi possível definir as opções do socket" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Não é possível definir o valor quando a direção é inserida." @@ -675,7 +700,7 @@ msgstr "Não é possível transferir sem os pinos MOSI e MISO." msgid "Cannot unambiguously get sizeof scalar" msgstr "Não é possível obter inequivocamente o tamanho do escalar" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "Não é possível variar a frequência em um timer que já esteja em uso" @@ -761,14 +786,6 @@ msgstr "Não foi possível inicializar o SDCard" msgid "Could not initialize UART" msgstr "Não foi possível inicializar o UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Não foi possível inicializar o canal" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Não foi possível inicializar o temporizador" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Não foi possível reiniciar o canal" @@ -789,7 +806,7 @@ msgstr "Não foi possível recuperar o clock" msgid "Could not set address" msgstr "Não foi possível definir o endereço" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "Não foi possível iniciar o PWM" @@ -890,11 +907,16 @@ msgstr "Houve uma falha na alocação da memória ESP-IDF" msgid "EXTINT channel already in use" msgstr "Canal EXTINT em uso" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Houve um erro no fluxo MIDI na posição %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Erro no regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "Erro: Falha na vinculação" @@ -945,15 +967,15 @@ msgstr "Tupla esperada com comprimento %d, obteve %d" msgid "Extended advertisements with scan response not supported." msgstr "Anúncios estendidos não compatíveis com a resposta da varredura." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "O FFT é definido apenas para ndarrays" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "O FFT é implementado apenas para matrizes lineares" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "Houve uma falha no handshake do SSL" @@ -967,6 +989,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Houve uma falha na aquisição do mutex, err 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Falha ao alocar buffer RX" @@ -975,6 +998,7 @@ msgstr "Falha ao alocar buffer RX" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -988,6 +1012,10 @@ msgstr "Houve uma falha na alocação da memória do Wifi" msgid "Failed to allocate wifi scan memory" msgstr "Houve uma falha na alocação da memória para a varredura do Wifi" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "Houve uma falha ao fazer uma memória prévia (buffer) da amostra" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Falha ao conectar: erro interno" @@ -1013,6 +1041,10 @@ msgstr "Houve uma falha ao liberar o mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Falha ao gravar o flash interno." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Erro fatal." + #: py/moduerrno.c msgid "File exists" msgstr "Arquivo já existe" @@ -1036,7 +1068,7 @@ msgstr "O formato não é suportado" msgid "Framebuffer requires %d bytes" msgstr "O Framebuffer requer %d bytes" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "" "A frequência deve coincidir com o PWMOut existente usando este temporizador" @@ -1056,10 +1088,6 @@ msgstr "Falha Genérica" msgid "Group already used" msgstr "O grupo já está em uso" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Grupo cheio" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1090,15 +1118,15 @@ msgstr "Periférico I2C em uso" msgid "I2SOut not available" msgstr "O I2SOut não está disponível" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOs 0, 2 e 4 não suportam pullup interno em repouso (sleep)" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "O IV deve ter %d bytes de comprimento" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "Os elementos In-buffer devem ter um comprimento de <= 4 bytes" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1115,10 +1143,29 @@ msgstr "O tamanho do buffer está incorreto" msgid "Init program size invalid" msgstr "O tamanho do programa Init é inválido" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" +"A direção da definição inicial do pino conflita com a direção inicial do " +"pino de saída" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" +"A definição do estado inicial do pino está em conflito com estado do inicial " +"do pino" + #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "A inicialização falhou devido à falta de memória" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" +"O comprimento do buffer de entrada (%d) deve ser um múltiplo da contagem dos " +"fios (%d)" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "A entrada está demorando demais" @@ -1175,6 +1222,7 @@ msgstr "%q Inválido" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Pino do %q inválido" @@ -1201,8 +1249,14 @@ msgstr "BSSID Inválido" msgid "Invalid DAC pin supplied" msgstr "O pino DAC informado é inválido" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "O arquivo MIDI é inválido" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Frequência PWM inválida" @@ -1220,7 +1274,8 @@ msgstr "Argumento inválido" msgid "Invalid bits per value" msgstr "Os valores por bits são inválidos" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "O tamanho do buffer é inválido" @@ -1249,14 +1304,10 @@ msgstr "Arquivo inválido" msgid "Invalid format chunk size" msgstr "Tamanho do pedaço de formato inválido" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Frequência inválida" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "A frequência informada é inválida" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "O acesso da memória é inválido." @@ -1295,17 +1346,13 @@ msgstr "Pino inválido para canal direito" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Pinos inválidos" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Os pinos para o PWMOut são inválidos" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1327,7 +1374,7 @@ msgstr "O Security_mode é inválido" msgid "Invalid size" msgstr "Tamanho inválido" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "Soquete inválido para o TLS" @@ -1335,10 +1382,6 @@ msgstr "Soquete inválido para o TLS" msgid "Invalid state" msgstr "Estado inválido" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "Uso inválido do soquete TLS" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "A voz é inválida" @@ -1351,14 +1394,11 @@ msgstr "A contagem da voz é inválida" msgid "Invalid wave file" msgstr "Aqruivo de ondas inválido" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "O comprimento do bit/palavra são inválidos" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "Problema na configuração do SO_REUSEADDR" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "A chave deve ter 16, 24 ou 32 bytes de comprimento" @@ -1404,14 +1444,6 @@ msgstr "O valor máximo de x quando espelhado é %d" msgid "Messages limited to 8 bytes" msgstr "As mensagens estão limitadas a 8 bytes" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "O salto do MicroPython NLR falhou. Possível corrupção de memória." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "Houve um erro fatal do MicroPython." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "O atraso na inicialização do microfone deve estar entre 0,0 e 1,0" @@ -1463,6 +1495,10 @@ msgstr "Deve informar os pinos MISO ou MOSI" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Deve utilizar um múltiplo de 6 pinos rgb, não %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "O salto NLR falhou. Possível corrupção da memória." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "Erro NVS" @@ -1482,9 +1518,15 @@ msgstr "Nenhum DAC no chip" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Nenhum canal DMA foi encontrado" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "Nenhum temporizador DMA foi encontrado" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1543,6 +1585,14 @@ msgstr "Sem suporte de hardware no pino de clock" msgid "No hardware support on pin" msgstr "Nenhum suporte de hardware no pino" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "Sem entrada no programa" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "Sem entrada ou saída no programa" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Nenhuma chave foi definida" @@ -1551,18 +1601,6 @@ msgstr "Nenhuma chave foi definida" msgid "No long integer support" msgstr "Não há compatibilidade com inteiro longo" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "Não há mais canais disponíveis" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "Não há mais temporizadores disponíveis" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "Não há mais temporizadores disponíveis neste pino." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "Não há rede com este ssid" @@ -1571,6 +1609,14 @@ msgstr "Não há rede com este ssid" msgid "No out in program" msgstr "Sem saída no programa" +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "" +"Nenhum pull up foi encontrado no SDA ou no SCL; verifique o fio das suas " +"conexões" + #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "Não há pulldown no pino; É recomendável utilizar um resistor de 1M ohm" @@ -1588,13 +1634,18 @@ msgid "No timer available" msgstr "Não há um temporizador disponível" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Declaração de falha do dispositivo Nordic Soft." +msgid "Nordic system firmware failure assertion." +msgstr "Declaração de falha do firmware do sistema nórdico." + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "O firmware do sistema nórdico está sem memória" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "Não é uma sequência válida de IP" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1624,13 +1675,10 @@ msgid "Odd parity is not supported" msgstr "A paridade ímpar não é compatível" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Apenas mono com 8 ou 16 bits com " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "Somente IN/OUT de até 8 suportados" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "Somente os endereços IPv4 são suportados" @@ -1684,10 +1732,19 @@ msgstr "A operação expirou" msgid "Out of memory" msgstr "Sem memória" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "Sem soquetes" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "Os elementos Out-buffer devem ter um comprimento de <= 4 bytes" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "O buffer de saída deve ter ao menos %d bytes" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "A superamostragem deve ser um múltiplo de 8." @@ -1710,8 +1767,15 @@ msgstr "" "A frequência do PWM não pode ser gravada quando variable_frequency for False " "na construção." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "A fatia do PWM já está em uso" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "O canal A da fatia do PWM já está em uso" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "O ParallelBus ainda não é compatível" @@ -1747,6 +1811,10 @@ msgstr "O pino não tem recursos de ADC" msgid "Pin is input only" msgstr "Apenas o pino de entrada" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "O pino deve estar no canal B do PWM" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "O pino deve ser compatível com as interrupções do hardware" @@ -1766,6 +1834,14 @@ msgstr "" "ideal. Caso isso não possa ser evitado, passe allow_inefficient=True ao " "construtor" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "Os pinos devem ser sequenciais" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "Os pinos devem compartilhar a fatia do PWM" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Além de quaisquer módulos no sistema de arquivos\n" @@ -1846,6 +1922,10 @@ msgstr "Erro DeInit RNG" msgid "RNG Init Error" msgstr "Houve um erro na inicialização do RNG" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "Ainda não há suporte para o RS485 neste dispositivo" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1853,6 +1933,7 @@ msgstr "A definição da inversão do RS485 quando não está no modo RS485" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "A calibração RTC não é suportada nesta placa" @@ -1861,7 +1942,7 @@ msgid "RTC is not supported on this board" msgstr "O RTC não é suportado nesta placa" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS/CTS/RS485 Ainda não é compatível neste dispositivo" @@ -1918,12 +1999,6 @@ msgstr "Executando no modo de segurança! " msgid "SD card CSD format not supported" msgstr "O formato CSD do Cartão SD não é compatível" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA ou SCL precisa de um pull up" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1959,14 +2034,6 @@ msgstr "Taxa de amostragem muito alta. Deve ser menor que %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "O escaneamento já está em andamento. Interrompa com stop_scan." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "O pino CTS selecionado é inválido" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "O pino RTS selecionado é inválido" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -2016,6 +2083,14 @@ msgstr "Divisão com sub-capturas" msgid "Stack size must be at least 256" msgstr "O tamanho da pilha deve ser pelo menos 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "O estéreo à esquerda deve estar no canal PWM A" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "O estéreo à direita deve estar no canal PWM B" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Transmita o método ausente readinto() ou write()." @@ -2111,18 +2186,12 @@ msgstr "" "O tempo limite é long demais: O comprimento máximo do tempo limite é de %d " "segundos" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" -"O temporizador foi reservado para uso interno - declare os pinos PWM no " -"início do programa" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Para sair, por favor, reinicie a placa sem " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Muitos canais na amostra." @@ -2135,9 +2204,8 @@ msgid "Too many displays" msgstr "Exibições demais" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "" -"O total dos dados que serão gravados é maior que outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "O total dos dados que serão escritos é maior do que %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2163,10 +2231,6 @@ msgstr "Houve um erro na inicialização do UART" msgid "UART Re-init error" msgstr "Houve um erro na reinicialização do UART" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "O UART ainda não é suportado" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "Houve um erro na gravação UART" @@ -2193,6 +2257,8 @@ msgstr "O valor UUID não é um buffer str, int ou byte" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Não é possível alocar buffers para conversão assinada" @@ -2230,7 +2296,7 @@ msgstr "Não foi possível escrever no sleep_memory." msgid "Unexpected nrfx uuid type" msgstr "Tipo uuid nrfx inesperado" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "Erro não tratado do ESP TLS %d %d %x %d" @@ -2256,8 +2322,8 @@ msgstr "Erro de segurança desconhecido: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Erro desconhecido do dispositivo de soft: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "Erro desconhecido do firmware: %04x" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2286,7 +2352,7 @@ msgstr "Não há suporte para o tipo do display bus" msgid "Unsupported format" msgstr "Formato não suportado" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Operação não suportada" @@ -2312,10 +2378,6 @@ msgstr "O comprimento do valor é > max_length" msgid "Version was invalid" msgstr "A versão era inválida" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Atualmente, as funções do Viper não suportam mais de 4 argumentos" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "O tempo limite de leitura da tensão expirou" @@ -2405,11 +2467,6 @@ msgstr "é necessário objetos tipo bytes" msgid "abort() called" msgstr "abort() chamado" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "endereço %08x não está alinhado com %d bytes" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "endereço fora dos limites" @@ -2418,15 +2475,19 @@ msgstr "endereço fora dos limites" msgid "addresses is empty" msgstr "os endereços estão vazios" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "o arg é uma sequência vazia" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "O argumento argsort deve ser um ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "argsort não é implementado para matrizes achatadas" @@ -2434,10 +2495,6 @@ msgstr "argsort não é implementado para matrizes achatadas" msgid "argument has wrong type" msgstr "argumento tem tipo errado" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "o argumento deve ser ndarray" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2447,7 +2504,8 @@ msgstr "o argumento num/tipos não combinam" msgid "argument should be a '%q' not a '%q'" msgstr "o argumento deve ser um '%q' e não um '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "os argumentos devem ser ndarrays" @@ -2460,11 +2518,11 @@ msgstr "a matriz e comprimento do índice devem ser iguais" msgid "array/bytes required on right side" msgstr "matriz/bytes são necessários no lado direito" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "tentativa de obter (arg)min/(arg)max da sequência vazia" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "tente obter argmin/argmax de uma sequência vazia" @@ -2472,15 +2530,15 @@ msgstr "tente obter argmin/argmax de uma sequência vazia" msgid "attributes not supported yet" msgstr "atributos ainda não suportados" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "o eixo está fora dos limites" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "eixo deve ser Nenhum ou um número inteiro" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "o eixo é muito longo" @@ -2505,8 +2563,8 @@ msgid "binary op %q not implemented" msgstr "a operação binário %q não foi implementada" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "os bits devem ser 7, 8 ou 9" +msgid "bits must be in range 5 to 9" +msgstr "os bits devem estar na faixa entre 5 a 9" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2516,15 +2574,11 @@ msgstr "bits_per_sample deve ser 8 ou 16" msgid "branch not in range" msgstr "ramo fora do alcance" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "o tamanho do buffer é menor do que o tamanho que foi solicitado" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "o buffer deve ser um objeto como bytes" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "o tamanho do buffer deve ser um múltiplo do tamanho do elemento" @@ -2541,7 +2595,7 @@ msgstr "as fatias do buffer devem ter o mesmo comprimento" msgid "buffer too small" msgstr "o buffer é muito pequeno" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "o buffer é pequeno demais para os bytes requisitados" @@ -2607,6 +2661,10 @@ msgstr "a expressão não pode ser atribuída" msgid "can't convert %q to %q" msgstr "não é possível converter %q para %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "não é possível converter implicitamente o objeto '%q' para %q" @@ -2615,6 +2673,10 @@ msgstr "não é possível converter implicitamente o objeto '%q' para %q" msgid "can't convert to %q" msgstr "não é possível converter para %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "não é possível converter para int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "não é possível converter implicitamente para str" @@ -2737,6 +2799,10 @@ msgstr "o arg chr() está fora do intervalo(256)" msgid "circle can only be registered in one parent" msgstr "o círculo só pode ser registrado em um pai" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "O ponto do clipe deve ser uma tupla (x, y)" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "código fora do alcance 0~127" @@ -2783,19 +2849,19 @@ msgstr "constante deve ser um inteiro" msgid "conversion to object" msgstr "conversão para o objeto" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "os argumentos convolutivos devem ser matrizes lineares" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "os argumentos convolutivos devem ser ndarrays" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "os argumentos convolutivos não devem estar vazios" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "não foi possível inverter a matriz Vandermonde" @@ -2803,15 +2869,15 @@ msgstr "não foi possível inverter a matriz Vandermonde" msgid "couldn't determine SD card version" msgstr "não foi possível determinar a versão do cartão SD" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "a cruz é definida para matrizes 1D de comprimento 3" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "os dados devem ser iteráveis" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "os dados devem ser de igual comprimento" @@ -2851,14 +2917,18 @@ msgstr "destination_length deve ser um int >= 0" msgid "dict update sequence has wrong length" msgstr "sequência da atualização dict tem o comprimento errado" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "O argumento diff deve ser um ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "ordem de diferenciação fora do alcance" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "as dimensões não coincidem" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2966,7 +3036,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: um único '}' não é permitido" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "o arquivo deve ser um arquivo aberto no modo byte" @@ -2974,11 +3044,11 @@ msgstr "o arquivo deve ser um arquivo aberto no modo byte" msgid "filesystem must provide mount method" msgstr "sistema de arquivos deve fornecer método de montagem" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "o primeiro argumento deve ser chamável" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "o primeiro argumento deve ser uma função" @@ -2986,11 +3056,7 @@ msgstr "o primeiro argumento deve ser uma função" msgid "first argument must be a tuple of ndarrays" msgstr "o primeiro argumento deve ser um tuple de ndarrays" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "o primeiro argumento deve ser um iterável" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "o primeiro argumento deve ser um ndarray" @@ -3002,7 +3068,7 @@ msgstr "o primeiro argumento para super() deve ser um tipo" msgid "flattening order must be either 'C', or 'F'" msgstr "a ordem do nivelamento deve ser 'C' ou 'F'" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "o argumento flip deve ser um ndarray" @@ -3023,8 +3089,8 @@ msgid "full" msgstr "cheio" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "função não aceita argumentos de palavras-chave" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3035,7 +3101,7 @@ msgstr "função esperada na maioria dos %d argumentos, obteve %d" msgid "function got multiple values for argument '%q'" msgstr "A função obteve vários valores para o argumento '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "a função tem o mesmo sinal nas extremidades do intervalo" @@ -3078,6 +3144,10 @@ msgstr "o gerador já está em execução" msgid "generator ignored GeneratorExit" msgstr "ignorando o gerador GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "o gráfico deve ter 2048 bytes de comprimento" @@ -3110,8 +3180,9 @@ msgstr "preenchimento incorreto" msgid "index is out of bounds" msgstr "o índice está fora dos limites" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "Índice fora do intervalo" @@ -3123,7 +3194,7 @@ msgstr "os índices devem ser inteiros" msgid "indices must be integers, slices, or Boolean lists" msgstr "os índices devem ser números inteiros, fatias ou listas booleanas" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "os valores iniciais devem ser iteráveis" @@ -3144,7 +3215,7 @@ msgid "input argument must be an integer, a tuple, or a list" msgstr "" "argumento da entrada deve ser um número inteiro, uma tupla ou uma lista" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "comprimento da matriz da entrada deve ter potência de 2" @@ -3152,15 +3223,15 @@ msgstr "comprimento da matriz da entrada deve ter potência de 2" msgid "input arrays are not compatible" msgstr "as matrizes da entrada não são compatíveis" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "os dados da entrada devem ser iteráveis" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "a matriz da entrada é assimétrica" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "a matriz da entrada é singular" @@ -3176,23 +3247,23 @@ msgstr "a entrada dos dados deve ser um tensor de nível 2" msgid "input must be an ndarray" msgstr "a entrada deve ser um ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "a entrada deve ser unidimensional" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "a entrada deve ser uma matriz quadrada" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "A entrada deve ser tupla, lista, intervalo ou matriz" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "os vetores da entrada devem ter o mesmo comprimento" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "as entradas não são iteráveis" @@ -3204,7 +3275,7 @@ msgstr "int() arg 2 deve ser >= 2 e <= 36" msgid "integer required" msgstr "inteiro requerido" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "o interp é definido para matrizes 1D de igual comprimento" @@ -3217,14 +3288,33 @@ msgstr "o intervalo deve estar entre %s-%s" msgid "invalid arguments" msgstr "argumentos inválidos" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "bits_per_pixel %d é inválido, deve ser, 1, 4, 8, 16, 24, ou 32" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "certificado inválido" +#: py/compile.c +msgid "invalid decorator" +msgstr "decorador inválido" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "Índice de dupterm inválido" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "tamanho do elemento %d é inválido para bits_per_pixel %d\n" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "element_size %d é inválido, deve ser, 1, 2, ou 4" + #: extmod/modframebuf.c msgid "invalid format" msgstr "formato inválido" @@ -3266,10 +3356,6 @@ msgstr "sintaxe inválida para o número inteiro com base %d" msgid "invalid syntax for number" msgstr "sintaxe inválida para o número" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "O io deve ser rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 deve ser uma classe" @@ -3278,11 +3364,7 @@ msgstr "issubclass() arg 1 deve ser uma classe" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass() arg 2 deve ser uma classe ou uma tupla de classes" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "os iteráveis não têm o mesmo comprimento" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "as iterações não convergiram" @@ -3353,11 +3435,7 @@ msgstr "o mapa do buffer é muito pequeno" msgid "math domain error" msgstr "erro de domínio matemático" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "as dimensões da matriz não coincidem" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "a matriz não é definitiva positiva" @@ -3379,15 +3457,15 @@ msgstr "O número máximo de dimensões são 4" msgid "maximum recursion depth exceeded" msgstr "a recursão máxima da profundidade foi excedida" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "maxiter deve ser > 0" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "maxiter pode ser > 0" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "o argumento mediano deve ser um ndarray" @@ -3402,11 +3480,15 @@ msgstr "" "falha na alocação de memória, a área de alocação dinâmica de variáveis " "(heap) está bloqueada" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "memoryview: o comprimento não é um múltiplo do tamanho dos itens" + #: py/builtinimport.c msgid "module not found" msgstr "o módulo não foi encontrado" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "mais graus de liberdade do que pontos de dados" @@ -3451,6 +3533,10 @@ msgstr "rendimento nativo" msgid "need more than %d values to unpack" msgstr "precisa de mais de %d valores para desempacotar" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "potência negativa sem suporte de flutuação" @@ -3524,10 +3610,6 @@ msgstr "o tempo limite não zero deve ser > 0.01" msgid "non-zero timeout must be >= interval" msgstr "o tempo limite não zero deve ser >= intervalo" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "a norma é definida para matrizes 1D e 2D" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "não é um UUID com 128 bits" @@ -3596,7 +3678,7 @@ msgstr "é necessário objeto com protocolo do buffer" msgid "odd-length string" msgstr "sequência com comprimento ímpar" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "o offset é muito grande" @@ -3626,8 +3708,8 @@ msgid "only slices with step=1 (aka None) are supported" msgstr "" "apenas fatias com a etapa=1 (também conhecida como Nenhuma) são compatíveis" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "os operandos não puderam ser transmitidos juntos" @@ -3635,7 +3717,7 @@ msgstr "os operandos não puderam ser transmitidos juntos" msgid "operation is implemented for 1D Boolean arrays only" msgstr "A operação é implementada apenas para matrizes booleanas 1D" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "a operação não foi implementada nos ndarrays" @@ -3654,11 +3736,19 @@ msgstr "" "o ord() esperava um caractere, porém a sequência do comprimento %d foi " "encontrada" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "a matriz externa é muito pequena" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "deve ser uma matriz densa flutuante" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "fora do alcance da fonte" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "fora do alcance do alvo" @@ -3681,10 +3771,6 @@ msgstr "a paleta deve ter 32 bytes de comprimento" msgid "palette_index should be an int" msgstr "palette_index deve ser um int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "a anotação do parâmetro deve ser um identificador" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "os parâmetros devem ser registradores na sequência a2 até a5" @@ -3693,7 +3779,7 @@ msgstr "os parâmetros devem ser registradores na sequência a2 até a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "os parâmetros devem ser registradores na sequência r0 até r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "as coordenadas do pixel estão fora dos limites" @@ -3716,11 +3802,16 @@ msgstr "pop a partir de um PulseIn vazio" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "pop a partir do %q vazio" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "a porta deve ser > = 0" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "O terceiro argumento pow() não pode ser 0" @@ -3731,12 +3822,17 @@ msgstr "o pow() com 3 argumentos requer números inteiros" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3744,6 +3840,7 @@ msgstr "o pow() com 3 argumentos requer números inteiros" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "pressionando o botão de boot na inicialização.\n" @@ -3755,6 +3852,14 @@ msgstr "pressionando o botão de boot na inicialização.\n" msgid "pressing both buttons at start up.\n" msgstr "pressionando ambos os botões durante a inicialização.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "pressionando o botão esquerdo durante a inicialização\n" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "puxe as máscaras em conflito com as máscaras de direção" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" msgstr "O pull_threshold deve ser entre 1 e 32" @@ -3771,7 +3876,7 @@ msgstr "estouro de fila" msgid "raw f-strings are not implemented" msgstr "o f-strings bruto não estão implementados" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "partes reais e imaginárias devem ter o mesmo comprimento" @@ -3806,7 +3911,7 @@ msgstr "rgb_pins[%d] duplica outra atribuição dos pinos" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins[%d] não está na mesma porta que o clock" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "argumento de enrolar deve ser um ndarray" @@ -3823,6 +3928,7 @@ msgstr "" "ou 'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "Taxa de amostragem fora do intervalo" @@ -3854,7 +3960,7 @@ msgstr "sinal não permitido com o especificador no formato inteiro 'c'" msgid "single '}' encountered in format string" msgstr "único '}' encontrado na string do formato" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "o tamanho é definido apenas para os ndarrays" @@ -3878,23 +3984,23 @@ msgstr "transbordamento int pequeno" msgid "soft reboot\n" msgstr "reinicialização soft\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "o argumento da classificação deve ser um ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "o sos da matriz deve estar na forma (n_section, 6)" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "sos[:, 3] deve ser um em todos" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "o sosfilt requer que os argumentos sejam iteráveis" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "a paleta de origem é muito grande" @@ -4004,7 +4110,7 @@ msgstr "os tobytes podem ser invocados apenas nas matrizes densas" msgid "too many arguments provided with the given format" msgstr "Muitos argumentos fornecidos com o formato dado" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "dimensões demais" @@ -4017,18 +4123,14 @@ msgstr "índices demais" msgid "too many values to unpack (expected %d)" msgstr "valores demais para descompactar (esperado %d)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "Trapz está definido para arrays 1D" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "o trapz está definido para 1D arrays de igual tamanho" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "nível do gatilho deve ser 0 ou 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "a tupla/lista está com tamanho incorreto" @@ -4110,7 +4212,7 @@ msgstr "o formato do código '%c' é desconhecido para o objeto do tipo '%q'" msgid "unknown type" msgstr "tipo desconhecido" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "tipo desconhecido '%q'" @@ -4163,14 +4265,6 @@ msgstr "o valor deve caber em %d byte(s)" msgid "value_count must be > 0" msgstr "o value_count deve ser > 0" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "os vetores devem ter os mesmos comprimentos" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "conflito de wakeup" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "o watchdog não foi inicializado" @@ -4179,6 +4273,11 @@ msgstr "o watchdog não foi inicializado" msgid "watchdog timeout must be greater than 0" msgstr "o tempo limite do watchdog deve ser maior que 0" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "a largura deve ser entre 2 a 8 (inclusive), não %d" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "a largura deve ser maior que zero" @@ -4191,7 +4290,7 @@ msgstr "o wifi não está ativo" msgid "window must be <= interval" msgstr "a janela deve ser <= intervalo" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "índice do eixo errado" @@ -4199,7 +4298,8 @@ msgstr "índice do eixo errado" msgid "wrong axis specified" msgstr "um eixo errado foi definido" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "tipo da entrada incorreta" @@ -4215,7 +4315,7 @@ msgstr "quantidade incorreta dos valores para descompressão" msgid "wrong operand type" msgstr "tipo do operando errado" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "tipo da saída incorreta" @@ -4239,18 +4339,152 @@ msgstr "o valor y está fora dos limites" msgid "zero step" msgstr "passo zero" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "zi deve ser um ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "zi deve ser de um tipo float" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "zi deve estar na forma (n_section, 2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Atualmente, as funções do Viper não suportam mais de 4 argumentos" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "endereço %08x não está alinhado com %d bytes" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "função não aceita argumentos de palavras-chave" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "a anotação do parâmetro deve ser um identificador" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "" +#~ "O total dos dados que serão gravados é maior que outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOs 0, 2 e 4 não suportam pullup interno em repouso (sleep)" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "o buffer deve ser um objeto como bytes" + +#~ msgid "io must be rtc io" +#~ msgstr "O io deve ser rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "nível do gatilho deve ser 0 ou 1" + +#~ msgid "wakeup conflict" +#~ msgstr "conflito de wakeup" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "" +#~ "A tentativa da área de alocação dinâmica de variáveis (heap) quando o " +#~ "MicroPython VM não está em execução." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "O salto do MicroPython NLR falhou. Possível corrupção de memória." + +#~ msgid "MicroPython fatal error." +#~ msgstr "Houve um erro fatal do MicroPython." + +#~ msgid "argument must be ndarray" +#~ msgstr "o argumento deve ser ndarray" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "as dimensões da matriz não coincidem" + +#~ msgid "norm is defined for 1D and 2D arrays" +#~ msgstr "a norma é definida para matrizes 1D e 2D" + +#~ msgid "vectors must have same lengths" +#~ msgstr "os vetores devem ter os mesmos comprimentos" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Declaração de falha do dispositivo Nordic Soft." + +#~ msgid "Nordic soft device out of memory" +#~ msgstr "O soft do dispositivo nórdico está sem memória" + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Erro desconhecido do dispositivo de soft: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "o primeiro argumento deve ser um iterável" + +#~ msgid "iterables are not of the same length" +#~ msgstr "os iteráveis não têm o mesmo comprimento" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "O pino CTS selecionado é inválido" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "O pino RTS selecionado é inválido" + +#~ msgid "Could not initialize channel" +#~ msgstr "Não foi possível inicializar o canal" + +#~ msgid "Could not initialize timer" +#~ msgstr "Não foi possível inicializar o temporizador" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "A frequência informada é inválida" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Os pinos para o PWMOut são inválidos" + +#~ msgid "No more channels available" +#~ msgstr "Não há mais canais disponíveis" + +#~ msgid "No more timers available" +#~ msgstr "Não há mais temporizadores disponíveis" + +#~ msgid "No more timers available on this pin." +#~ msgstr "Não há mais temporizadores disponíveis neste pino." + +#~ msgid "" +#~ "Timer was reserved for internal use - declare PWM pins earlier in the " +#~ "program" +#~ msgstr "" +#~ "O temporizador foi reservado para uso interno - declare os pinos PWM no " +#~ "início do programa" + +#~ msgid "Group full" +#~ msgstr "Grupo cheio" + +#~ msgid "In buffer elements must be 4 bytes long or less" +#~ msgstr "No buffer, os elementos devem ter 4 bytes ou menos" + +#~ msgid "Out buffer elements must be 4 bytes long or less" +#~ msgstr "Os elementos da saída do buffer devem ter 4 bytes ou menos" + +#~ msgid "Initial set pin direcion conflicts with initial out pin direction" +#~ msgstr "" +#~ "A direção do pino inicial está em conflito com a direção inicial do pino" + +#~ msgid "UART not yet supported" +#~ msgstr "O UART ainda não é suportado" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "os bits devem ser 7, 8 ou 9" + +#~ msgid "Only IN/OUT of up to 8 supported" +#~ msgstr "Somente IN/OUT de até 8 suportados" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA ou SCL precisa de um pull up" + +#~ msgid "Invalid use of TLS Socket" +#~ msgstr "Uso inválido do soquete TLS" + +#~ msgid "Issue setting SO_REUSEADDR" +#~ msgstr "Problema na configuração do SO_REUSEADDR" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "" #~ "%d endereços dos pinos e %d pinos rgb indicam uma altura do %d, não %d" @@ -4451,9 +4685,6 @@ msgstr "zi deve estar na forma (n_section, 2)" #~ msgid "can't convert to float" #~ msgstr "não é possível converter para float" -#~ msgid "can't convert to int" -#~ msgstr "não é possível converter para int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "o objeto '%s' não é uma tupla ou uma lista" diff --git a/locale/sv.po b/locale/sv.po index c4c51fcc00716..29d7e22ca26db 100644 --- a/locale/sv.po +++ b/locale/sv.po @@ -6,7 +6,7 @@ msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-01-25 19:32+0000\n" +"PO-Revision-Date: 2021-04-23 12:37+0000\n" "Last-Translator: Jonny Bergdahl \n" "Language-Team: LANGUAGE \n" "Language: sv\n" @@ -14,7 +14,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" -"X-Generator: Weblate 4.5-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -68,6 +68,7 @@ msgstr "%%c kräver int eller char" msgid "" "%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" msgstr "" +"%d adresspinnar, %d rgb-stift och %d brickor anger en höjd på %d, inte %d" #: ports/atmel-samd/common-hal/sdioio/SDCard.c msgid "%q failure: %d" @@ -80,6 +81,7 @@ msgstr "%q används redan" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -109,6 +111,7 @@ msgstr "%q måste vara >= 1" msgid "%q must be a tuple of length 2" msgstr "%q måste vara en tuple av längd 2" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q utanför intervallet" @@ -123,7 +126,7 @@ msgstr "%q ska vara en int" #: py/bc.c py/objnamedtuple.c msgid "%q() takes %d positional arguments but %d were given" -msgstr "%q() kräver %d positionsargument men %d gavs" +msgstr "% q () tar% d positionsargument men% d gavs" #: ports/esp32s2/bindings/espidf/__init__.c ports/esp32s2/esp_error.c #, c-format @@ -339,16 +342,21 @@ msgid "All SPI peripherals are in use" msgstr "All SPI-kringutrustning används" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Alla UART-kringutrustning används" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "Alla kanaler används" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Alla händelsekanaler används" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "All state machines in use" -msgstr "" +msgstr "Alla tillståndsmaskiner används" #: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "All sync event channels in use" @@ -370,6 +378,7 @@ msgstr "Alla timers för denna pinne är i bruk" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Alla timers används" @@ -410,6 +419,10 @@ msgstr "AnalogOut hanterar bara 16 bitar. Värdet måste vara mindre än 65536." msgid "AnalogOut not supported on given pin" msgstr "AnalogOut stöds inte på angiven pinne" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "En annan PWMAudioOut är redan aktiv" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -433,8 +446,8 @@ msgid "Attempt to allocate %d blocks" msgstr "Försök att tilldela %d block" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "Försökte tilldela heap när MicroPython VM inte körs." +msgid "Attempted heap allocation when VM not running." +msgstr "Försök till heap-allokering när den virtuella maskinen inte är igång." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -461,6 +474,10 @@ msgstr "Baudrate stöds inte av kringutrustning" msgid "Below minimum frame rate" msgstr "Under minsta bildfrekvens" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "Bitklocka och word select måste vara sekventiella pinnar" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Bitklocka och ordval måste dela en klockenhet" @@ -502,6 +519,10 @@ msgstr "Ljusstyrka kan inte justeras" msgid "Buffer + offset too small %d %d %d" msgstr "Buffert + offset för liten %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Buffertelement måste vara fyra byte långa eller mindre" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -518,6 +539,7 @@ msgid "Buffer is too small" msgstr "Bufferten är för liten" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "Buffertlängd %d för stor. Den måste vara mindre än %d" @@ -547,6 +569,7 @@ msgstr "Buffert är %d bytes för kort" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Busspinne %d används redan" @@ -641,6 +664,10 @@ msgid "Cannot reset into bootloader because no bootloader is present." msgstr "" "Det går inte att återställa till bootloader eftersom bootloader saknas." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "Det går inte att ange socketalternativ" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Kan inte sätta värde när riktning är input." @@ -662,7 +689,7 @@ msgstr "Kan inte överföra utan MOSI- och MISO-pinnar." msgid "Cannot unambiguously get sizeof scalar" msgstr "Kan inte entydigt få sizeof scalar" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "Det går inte att ändra frekvensen på en timer som redan används" @@ -748,14 +775,6 @@ msgstr "Kan inte initiera SD-kort" msgid "Could not initialize UART" msgstr "Det gick inte att initiera UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Det gick inte att initiera kanalen" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Det gick inte att initialisera timern" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Det gick inte att återinitiera kanalen" @@ -776,7 +795,7 @@ msgstr "Kunde inte hämta klocka" msgid "Could not set address" msgstr "Kan inte ange adress" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "Det gick inte att starta PWM" @@ -825,7 +844,7 @@ msgstr "Datapinne 0 måste vara bytejusterad" #: ports/esp32s2/common-hal/displayio/ParallelBus.c msgid "Data 0 pin must be byte aligned." -msgstr "" +msgstr "Datapinne 0 måste vara byte-justerad." #: shared-module/audiocore/WaveFile.c msgid "Data chunk must follow fmt chunk" @@ -877,11 +896,16 @@ msgstr "ESP-IDF-minnetilldelning misslyckades" msgid "EXTINT channel already in use" msgstr "EXTINT-kanalen används redan" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "Fel i MIDI-ström vid position %d" + #: extmod/modure.c msgid "Error in regex" msgstr "Fel i regex" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "Fel: Bind misslyckades" @@ -932,15 +956,15 @@ msgstr "Förväntad tupel med längd %d, fick %d" msgid "Extended advertisements with scan response not supported." msgstr "Utökad annonsering i kombination med skanningssvar stöds inte." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "FFT är enbart definierade för ndarrays" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "FTT är enbart implementerad för linjära matriser" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "Misslyckad SSL-handskakning" @@ -954,6 +978,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Det gick inte att förvärva mutex, fel 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Det gick inte att tilldela RX-buffert" @@ -962,6 +987,7 @@ msgstr "Det gick inte att tilldela RX-buffert" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -975,6 +1001,10 @@ msgstr "Det gick inte att allokera WiFi-minne" msgid "Failed to allocate wifi scan memory" msgstr "Det gick inte att allokera minne för WiFi-scanning" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "Det gick inte att buffra samplingen" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Det gick inte att ansluta: internt fel" @@ -1000,6 +1030,10 @@ msgstr "Det gick inte att frigöra mutex, fel 0x%04x" msgid "Failed to write internal flash." msgstr "Det gick inte att skriva till intern flash." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "Fatalt fel." + #: py/moduerrno.c msgid "File exists" msgstr "Filen finns redan" @@ -1023,7 +1057,7 @@ msgstr "Formatet stöds inte" msgid "Framebuffer requires %d bytes" msgstr "Framebuffer kräver %d byte" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "Frekvensen måste matcha befintlig PWMOut med denna timer" @@ -1042,10 +1076,6 @@ msgstr "Generiskt fel" msgid "Group already used" msgstr "Grupp används redan" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Gruppen är full" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1070,21 +1100,21 @@ msgstr "I2C init-fel" #: ports/raspberrypi/common-hal/busio/I2C.c msgid "I2C peripheral in use" -msgstr "" +msgstr "I2C-enhet används redan" #: shared-bindings/audiobusio/I2SOut.c msgid "I2SOut not available" msgstr "I2SOut är inte tillgängligt" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IO 0, 2 & 4 stöder inte intern pullup för sovläge" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IV måste vara %d byte lång" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "Antal element i buffert måste vara <= 4 byte" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1099,12 +1129,27 @@ msgstr "Fel buffertstorlek" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Init program size invalid" +msgstr "Storlek på init-program ogiltigt" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "Initial pinn-riktning står i konflikt med initial utpinns-riktning" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" msgstr "" +"Initial inställning av pinntillstånd är i konflikt med initialt " +"utpinntillstånd" #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "Initieringen misslyckades på grund av minnesbrist" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "indatabuffertlängd (%d) måste vara en multipel av antal strand (%d)" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "Indata tar för lång tid" @@ -1116,27 +1161,27 @@ msgstr "Indata-/utdatafel" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d jumps on pin" -msgstr "" +msgstr "Instruktion %d hoppar på pinne" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts in more bits than pin count" -msgstr "" +msgstr "Instruktion %d skiftar fler bitar än antalet pinnar" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts out more bits than pin count" -msgstr "" +msgstr "Instruktion %d skiftar fler bitar än antal pinnar" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d uses extra pin" -msgstr "" +msgstr "Instruktion %d använder extra pinne" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d waits on input outside of count" -msgstr "" +msgstr "Instruktion %d väntar på inmatning utanför intervallet" #: ports/nrf/common-hal/_bleio/__init__.c msgid "Insufficient authentication" @@ -1161,6 +1206,7 @@ msgstr "Ogiltig %q" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Ogiltig %q-pinne" @@ -1187,8 +1233,14 @@ msgstr "Ogiltig BSSID" msgid "Invalid DAC pin supplied" msgstr "Ogiltig DAC-pinne angiven" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "Ogiltig MIDI-fil" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Ogiltig PWM-frekvens" @@ -1206,7 +1258,8 @@ msgstr "Ogiltigt argument" msgid "Invalid bits per value" msgstr "Ogiltigt värde för bitar per värde" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Ogiltig buffertstorlek" @@ -1235,14 +1288,10 @@ msgstr "Felaktig fil" msgid "Invalid format chunk size" msgstr "Ogiltig formatsegmentstorlek" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Ogiltig frekvens" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Ogiltig frekvens angiven" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Ogiltig minnesåtkomst." @@ -1281,17 +1330,13 @@ msgstr "Ogiltig pinne för höger kanal" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Ogiltiga pinnar" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "Ogiltiga pinnar för PWMOut" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1313,7 +1358,7 @@ msgstr "Ogiltigt säkerhetsläge" msgid "Invalid size" msgstr "Ogiltig storlek" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "Ogiltig socket för TLS" @@ -1321,10 +1366,6 @@ msgstr "Ogiltig socket för TLS" msgid "Invalid state" msgstr "Ogiltigt tillstånd" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "Ogiltig användning av TLS Socket" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "Ogiltig kanal" @@ -1337,14 +1378,11 @@ msgstr "Ogiltigt kanalantal" msgid "Invalid wave file" msgstr "Ogiltig wave-fil" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Ogiltig word-/bitlängd" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "Misslyckades att sätta SO_REUSEADDR" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "Nyckeln måste vara 16, 24 eller 32 byte lång" @@ -1390,14 +1428,6 @@ msgstr "Maximum x-värde vid spegling är %d" msgid "Messages limited to 8 bytes" msgstr "Meddelanden begränsad till 8 byte" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR jump misslyckades. Troligen korrupt minne." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython fatalt fel." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "" @@ -1410,32 +1440,32 @@ msgstr "MISO- eller MOSI-pinne saknas" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d reads pin(s)" -msgstr "" +msgstr "Saknad first_in_pin. Instruktion %d läser pinnar" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d shifts in from pin(s)" -msgstr "" +msgstr "Saknad first_in_pin. Instruktion %d skiftar in från pinnar" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d waits based on pin" -msgstr "" +msgstr "Saknad first_in_pin. Instruktion %d väntar baserat på pinne" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d shifts out to pin(s)" -msgstr "" +msgstr "Saknad first_out_pin. Instruktion %d skiftar ut till pinnar" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d writes pin(s)" -msgstr "" +msgstr "Saknad first_out_pin. Instruktion %d skriver till pinnar" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_set_pin. Instruction %d sets pin(s)" -msgstr "" +msgstr "Saknad first_set_pin. Instruktion %d sätter pinnar" #: shared-bindings/displayio/Group.c msgid "Must be a %q subclass." @@ -1450,6 +1480,10 @@ msgstr "Måste ange MISO- eller MOSI-pinne" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "Måste använda ett multipel av 6 rgb-pinnar, inte %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "NLR jump misslyckades. Troligen korrupt minne." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS-fel" @@ -1469,9 +1503,15 @@ msgstr "Ingen DAC på chipet" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Ingen DMA-kanal hittades" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "Ingen DMA pacing timer hittades" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1530,6 +1570,14 @@ msgstr "Inget hårdvarustöd på clk-pinne" msgid "No hardware support on pin" msgstr "Inget hårdvarustöd på pinne" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "Inget in i programmet" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "Inget in eller ut i programmet" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Ingen nyckel angavs" @@ -1538,25 +1586,19 @@ msgstr "Ingen nyckel angavs" msgid "No long integer support" msgstr "Inget stöd för långt heltal" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "Inga fler kanaler tillgängliga" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "Ingen timer tillgänglig" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "Inga fler timers tillgängliga på denna pinne." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "Inget nätverk med sådant ssid" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No out in program" -msgstr "" +msgstr "Inget out i programmet" + +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "Ingen pull-up hittades på SDA eller SCL; kontrollera inkopplingen" #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" @@ -1575,13 +1617,18 @@ msgid "No timer available" msgstr "Ingen timer tillgänglig" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Påståendet om Nordic Soft Device-fel." +msgid "Nordic system firmware failure assertion." +msgstr "Felaktigt tillstånd i Nordic systemfirmware." + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "Nordic systemfirmware fick slut på minne" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "Inte en giltig IP-sträng" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1612,13 +1659,10 @@ msgid "Odd parity is not supported" msgstr "Udda paritet stöds inte" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Endast 8 eller 16 bitars mono med " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "Endast IPv4-adresser stöds" @@ -1671,10 +1715,19 @@ msgstr "Åtgärden orsakade timeout" msgid "Out of memory" msgstr "Slut på minne" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "Slut på sockets" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "Element i utbuffer måste vara <= 4 byte långa" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "Utdatabuffert måste vara minst %d byte" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Översampling måste vara multipel av 8." @@ -1695,8 +1748,15 @@ msgstr "" "PWM-frekvensen är inte skrivbar när variable_frequency är falsk vid " "skapandet." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "PWM-segment används redan" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "PWM-segmentkanal A används redan" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "ParallelBus stöds ännu inte" @@ -1711,11 +1771,11 @@ msgstr "Åtkomst nekad" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Pin count must be at least 1" -msgstr "" +msgstr "Antalet pinnar måste vara minst 1" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Pin count too large" -msgstr "" +msgstr "Antal pinnar för stort" #: ports/atmel-samd/common-hal/analogio/AnalogIn.c #: ports/cxd56/common-hal/analogio/AnalogIn.c @@ -1732,6 +1792,10 @@ msgstr "Pinnen har inte ADC-funktionalitet" msgid "Pin is input only" msgstr "Pinnen är enbart ingång" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "Pinne måste vara på PWM-kanal B" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "Pinnen måste stödja hårdvaruavbrott" @@ -1751,6 +1815,14 @@ msgstr "" "%d byte. Om detta inte kan undvikas, skicka allow_inefficient=True till " "konstruktorn" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "Pinnarna måste vara i sekvens" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "Pinnar måste dela PWM-segment" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Plus eventuella moduler i filsystemet\n" @@ -1794,23 +1866,23 @@ msgstr "Fingerar djup sömn tills larm, Ctrl-C eller filskrivning.\n" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does IN without loading ISR" -msgstr "" +msgstr "Program gör IN utan att ladda ISR" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does OUT without loading OSR" -msgstr "" +msgstr "Program gör OUT utan att läsa in OSR" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program must contain at least one 16-bit instruction." -msgstr "" +msgstr "Programmet måste innehålla minst en 16-bitars instruktion." #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program size invalid" -msgstr "" +msgstr "Programstorlek ogiltig" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program too large" -msgstr "" +msgstr "Programmet är för stort" #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." @@ -1818,7 +1890,7 @@ msgstr "Pull används inte när riktningen är output." #: ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c msgid "RAISE mode is not implemented" -msgstr "" +msgstr "RAISE-läge är inte implementerat" #: ports/stm/common-hal/os/__init__.c msgid "RNG DeInit Error" @@ -1828,6 +1900,10 @@ msgstr "RNG DeInit-fel" msgid "RNG Init Error" msgstr "RNG Init-fel" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "RS485 stöds ännu inte på den här enheten" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1835,6 +1911,7 @@ msgstr "RS485-inversion specificerad när den inte är i RS485-läge" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "RTC-kalibrering stöds inte av detta kort" @@ -1843,7 +1920,7 @@ msgid "RTC is not supported on this board" msgstr "RTC stöds inte av detta kort" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS/CTS/RS485 Stöds ännu inte på den här enheten" @@ -1900,12 +1977,6 @@ msgstr "Kör i säkert läge! " msgid "SD card CSD format not supported" msgstr "SD-kort CSD-format stöds inte" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA eller SCL behöver en pullup" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1926,7 +1997,7 @@ msgstr "SPI reinitialiseringsfel" #: ports/raspberrypi/common-hal/busio/SPI.c msgid "SPI peripheral in use" -msgstr "" +msgstr "SPI-enhet används redan" #: shared-bindings/audiomixer/Mixer.c msgid "Sample rate must be positive" @@ -1941,14 +2012,6 @@ msgstr "Samplingsfrekvensen är för hög. Den måste vara mindre än %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "Skanning pågår redan. Avsluta med stop_scan." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "Vald CTS-pinne är inte giltig" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "Vald CTS-pinne är inte giltig" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1960,11 +2023,11 @@ msgstr "Serversidans kontext kan inte ha värdnamn" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Set pin count must be between 1 and 5" -msgstr "" +msgstr "Inställt antal pinnar måste vara mellan 1 och 5" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Side set pin count must be between 1 and 5" -msgstr "" +msgstr "Sido-setets antal pinnar måste vara mellan 1 och 5" #: ports/cxd56/common-hal/camera/Camera.c msgid "Size not supported" @@ -1997,6 +2060,14 @@ msgstr "Splitting med sub-captures" msgid "Stack size must be at least 256" msgstr "Stackstorleken måste vara minst 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "Vänster stereokanal måste använda PWM kanal A" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "Höger stereokanal måste använda PWM kanal B" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Stream saknar readinto() eller write() metod." @@ -2089,18 +2160,12 @@ msgstr "Tid har passerats." msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "Åtgärden tog för lång tid: Max väntetid är %d sekunder" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" -"Timern är reserverad för internt bruk - deklarera PWM-pinne tidigare i " -"programmet" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "För att avsluta, gör reset på kortet utan " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "För många kanaler i sampling." @@ -2113,8 +2178,8 @@ msgid "Too many displays" msgstr "För många displayer" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "Total data som ska skrivas är större än outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "Totala data att skriva är större än %q" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2140,10 +2205,6 @@ msgstr "UART Init-fel" msgid "UART Re-init error" msgstr "UART reinit-fel" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "UART skrivfel" @@ -2170,6 +2231,8 @@ msgstr "UUID-värdet är inte str, int eller byte-buffert" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Det går inte att allokera buffert för signerad konvertering" @@ -2207,10 +2270,10 @@ msgstr "Det gick inte att skriva till sleep_memory." msgid "Unexpected nrfx uuid type" msgstr "Oväntad nrfx uuid-typ" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" -msgstr "Ej hanterat ESP TLS-fel %d-%d-%x-%d" +msgstr "Ej hanterat ESP TLS-fel %d %d %x %d" #: shared-bindings/wifi/Radio.c #, c-format @@ -2233,8 +2296,8 @@ msgstr "Okänt säkerhetsfel: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Okänt mjukvarufel: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "Okänt systemfirmwarefel: %04x" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2263,7 +2326,7 @@ msgstr "Busstyp för display stöds inte" msgid "Unsupported format" msgstr "Formatet stöds inte" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Åtgärd som inte stöds" @@ -2289,10 +2352,6 @@ msgstr "Värdets längd > max_length" msgid "Version was invalid" msgstr "Versionen var ogiltig" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper-funktioner stöder för närvarande inte mer än fyra argument" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Avläsning av spänning tog för lång tid" @@ -2378,11 +2437,6 @@ msgstr "ett bytesliknande objekt krävs" msgid "abort() called" msgstr "abort() anropad" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "adressen %08x är inte justerad till %d byte" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "adress utanför gränsen" @@ -2391,15 +2445,19 @@ msgstr "adress utanför gränsen" msgid "addresses is empty" msgstr "adresserna är tomma" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "Annoteringen måste vara en identifierare" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "arg är en tom sekvens" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "argumentet argsort måste vara en ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "argsort är inte implementerad för tillplattade matriser" @@ -2407,10 +2465,6 @@ msgstr "argsort är inte implementerad för tillplattade matriser" msgid "argument has wrong type" msgstr "argumentet har fel typ" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "argument måste vara ndarray" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2420,7 +2474,8 @@ msgstr "argument antal/typ matchar inte" msgid "argument should be a '%q' not a '%q'" msgstr "argumentet skall vara en '%q', inte en '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "argumenten måste vara ndarray" @@ -2433,11 +2488,11 @@ msgstr "array och indexlängd måste vara lika" msgid "array/bytes required on right side" msgstr "array/bytes krävs på höger sida" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "försök att läsa (arg)min/(arg)max av tom sekvens" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "försök att få argmin/argmax för en tom sekvens" @@ -2445,15 +2500,15 @@ msgstr "försök att få argmin/argmax för en tom sekvens" msgid "attributes not supported yet" msgstr "attribut stöds inte än" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "axis är utanför gränsen" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "axis måste vara None eller ett heltal" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "axis för lång" @@ -2478,8 +2533,8 @@ msgid "binary op %q not implemented" msgstr "binär op %q är inte implementerad" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bits måste vara 7, 8 eller 9" +msgid "bits must be in range 5 to 9" +msgstr "bits måste mellan 5 och 9" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2489,15 +2544,11 @@ msgstr "bits_per_sample måste vara 8 eller 16" msgid "branch not in range" msgstr "branch utanför räckvidd" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "bufferten är mindre än begärd storlek" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "buffer måste vara en byte-liknande objekt" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "buffertstorlek måste vara en multipel av elementstorlek" @@ -2514,7 +2565,7 @@ msgstr "buffertsegmenten måste vara lika långa" msgid "buffer too small" msgstr "buffert för liten" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "buffert för liten för begärd längd" @@ -2580,6 +2631,10 @@ msgstr "kan inte tilldela uttryck" msgid "can't convert %q to %q" msgstr "kan inte konvertera %q till %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "kan inte konvertera %q till int" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "kan inte konvertera '%q' objekt implicit till %q" @@ -2588,6 +2643,10 @@ msgstr "kan inte konvertera '%q' objekt implicit till %q" msgid "can't convert to %q" msgstr "kan inte konvertera till %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "kan inte konvertera till int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "kan inte implicit konvertera till str" @@ -2708,6 +2767,10 @@ msgstr "chr() arg är inte i intervallet(256)" msgid "circle can only be registered in one parent" msgstr "circle kan endast registreras i en förälder" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "klipppunkten måste vara en tuple (x,y)" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "kod utanför intervallet 0~127" @@ -2752,19 +2815,19 @@ msgstr "konstant måste vara ett heltal" msgid "conversion to object" msgstr "konvertering till objekt" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "Argumenten convolve måste vara linjära matriser" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "Argumenten convolve måste vara ndarray:er" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "Argumenten convolve kan inte vara tomma" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "kan inte invertera Vandermonde-matris" @@ -2772,15 +2835,15 @@ msgstr "kan inte invertera Vandermonde-matris" msgid "couldn't determine SD card version" msgstr "kan inte avgöra SD-kortversion" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "cross är definierad för 1D-matriser med längd 3" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "data måste vara itererbar" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "data måste vara av samma längd" @@ -2820,14 +2883,18 @@ msgstr "destination_length måste vara ett heltal >= 0" msgid "dict update sequence has wrong length" msgstr "uppdateringssekvensen för dict har fel längd" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "argumentet diff måste vara en ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "differentieringsordning utanför intervallet" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "dimensioner matchar inte" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2935,7 +3002,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: singel '}' är inte tillåten" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "filen måste vara en fil som öppnats i byte-läge" @@ -2943,11 +3010,11 @@ msgstr "filen måste vara en fil som öppnats i byte-läge" msgid "filesystem must provide mount method" msgstr "filsystemet måste tillhandahålla mount-metod" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "första argumentet måste vara en callable" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "första argumentet måste vara en funktion" @@ -2955,11 +3022,7 @@ msgstr "första argumentet måste vara en funktion" msgid "first argument must be a tuple of ndarrays" msgstr "första argumentet måste vara en tupel av ndarray" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "första argumentet måste vara en iterable" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "första argumentet måste vara en ndarray" @@ -2971,7 +3034,7 @@ msgstr "första argumentet till super() måste vara typ" msgid "flattening order must be either 'C', or 'F'" msgstr "förenklingsordningen måste vara antingen \"C\" eller \"F\"" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "Argumentet flip måste vara en ndarray" @@ -2992,7 +3055,7 @@ msgid "full" msgstr "full" #: py/argcheck.c -msgid "function does not take keyword arguments" +msgid "function doesn't take keyword arguments" msgstr "funktionen tar inte nyckelordsargument" #: py/argcheck.c @@ -3004,7 +3067,7 @@ msgstr "funktionen förväntar som mest %d argument, fick %d" msgid "function got multiple values for argument '%q'" msgstr "funktionen fick flera värden för argumentet '%q'" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "funktionen har samma teckenvärden vid slutet av intervall" @@ -3047,6 +3110,10 @@ msgstr "generatorn kör redan" msgid "generator ignored GeneratorExit" msgstr "generatorn ignorerade GeneratorExit" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "generator kastade StopIteration" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "graphic måste vara 2048 byte lång" @@ -3079,8 +3146,9 @@ msgstr "felaktig utfyllnad" msgid "index is out of bounds" msgstr "index är utanför gränserna" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "index utanför intervallet" @@ -3092,7 +3160,7 @@ msgstr "index måste vara heltal" msgid "indices must be integers, slices, or Boolean lists" msgstr "index måste vara heltal, slices, eller Boolean-listor" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "initialvärden måste vara iterable" @@ -3112,7 +3180,7 @@ msgstr "indata- och utdataformer är inte kompatibla" msgid "input argument must be an integer, a tuple, or a list" msgstr "indataargument måste vara integer, en tuple eller list" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "indataarraylängden måste vara en multipel av 2" @@ -3120,15 +3188,15 @@ msgstr "indataarraylängden måste vara en multipel av 2" msgid "input arrays are not compatible" msgstr "indatamatriser är inte kompatibla" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "indata måste vara en iterable" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "indatamatrisen är asymmetrisk" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "indatamatrisen är singulär" @@ -3144,23 +3212,23 @@ msgstr "indata måste vara en tensor av rank 2" msgid "input must be an ndarray" msgstr "indata måste vara en ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "indata måste vara endimensionell" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "indata måste vara kvadratmatris" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "indata måste vara tupel, lista, range, eller ndarray" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "indatavektorer måste ha samma längd" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "indata är inte iterbara" @@ -3172,7 +3240,7 @@ msgstr "int() arg 2 måste vara >= 2 och <= 36" msgid "integer required" msgstr "heltal krävs" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "interp är definierad för 1D-matriser med samma längd" @@ -3185,14 +3253,33 @@ msgstr "interval måste vara i intervallet %s-%s" msgid "invalid arguments" msgstr "ogiltiga argument" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "ogiltig bits_per_pixel %d, måste vara 1, 4, 8, 16, 24 eller 32" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "ogiltigt certifikat" +#: py/compile.c +msgid "invalid decorator" +msgstr "ogiltig dekorator" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "ogiltigt dupterm index" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "ogiltig elementstorlek %d för bits_per_pixel %d\n" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "ogiltig element_size %d, måste vara, 1, 2 eller 4" + #: extmod/modframebuf.c msgid "invalid format" msgstr "ogiltigt format" @@ -3234,10 +3321,6 @@ msgstr "ogiltig syntax för heltal med bas %d" msgid "invalid syntax for number" msgstr "ogiltig syntax för tal" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "io måste vara rtc io" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() arg 1 måste vara en klass" @@ -3246,11 +3329,7 @@ msgstr "issubclass() arg 1 måste vara en klass" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass() arg 2 måste vara en klass eller en tupel av klasser" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "iterables är inte av samma längd" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "iterations konvergerar inte" @@ -3321,11 +3400,7 @@ msgstr "map-buffert för liten" msgid "math domain error" msgstr "matematikdomänfel" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "matrisdimensioner matchar inte" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "matrisen är inte positiv bestämd" @@ -3347,15 +3422,15 @@ msgstr "maximalt antal dimensioner är 4" msgid "maximum recursion depth exceeded" msgstr "maximal rekursionsdjup överskriden" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "maxiter måste vara > 0" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "maxiter bör vara > 0" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "argumentet median måste vara en ndarray" @@ -3368,11 +3443,15 @@ msgstr "minnesallokering misslyckades, allokerar %u byte" msgid "memory allocation failed, heap is locked" msgstr "minnesallokeringen misslyckades, heapen är låst" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "memoryview: längden är inte en multipel av itemsize" + #: py/builtinimport.c msgid "module not found" msgstr "modulen hittades inte" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "fler frihetsgrader än datapunkter" @@ -3417,6 +3496,10 @@ msgstr "native yield" msgid "need more than %d values to unpack" msgstr "behöver mer än %d värden för att packa upp" +#: py/modmath.c +msgid "negative factorial" +msgstr "negativ faktoriell" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "negativ exponent utan stöd för flyttal" @@ -3490,10 +3573,6 @@ msgstr "Icke-noll timeout måste vara > 0.01" msgid "non-zero timeout must be >= interval" msgstr "Icke-noll timeout måste vara >= intervall" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "norm är definierad för 1D- och 2D-matriser" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "inte en 128-bitars UUID" @@ -3562,7 +3641,7 @@ msgstr "objekt med buffertprotokoll krävs" msgid "odd-length string" msgstr "sträng har udda längd" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "offset är för stor" @@ -3591,8 +3670,8 @@ msgstr "enbart sample_rate=16000 stöds" msgid "only slices with step=1 (aka None) are supported" msgstr "endast segment med steg=1 (aka Ingen) stöds" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "operander kan inte sändas tillsammans" @@ -3600,7 +3679,7 @@ msgstr "operander kan inte sändas tillsammans" msgid "operation is implemented for 1D Boolean arrays only" msgstr "operationen är enbart implementerad för 1D Boolean-matriser" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "åtgärden är inte implementerad för ndarray:er" @@ -3617,11 +3696,19 @@ msgstr "ord förväntar sig ett tecken" msgid "ord() expected a character, but string of length %d found" msgstr "ord() förväntade sig ett tecken, men en sträng med längden %d hittades" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "matrisen för out är för liten" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "out måste vara en float dense array" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "utanför räckvidd för source" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "utanför räckvidd för target" @@ -3642,10 +3729,6 @@ msgstr "palette måste vara 32 bytes lång" msgid "palette_index should be an int" msgstr "palette_index ska vara en int" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "parametern annotation måste vara en identifierare" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "parametrarna måste registreras i följd a2-a5" @@ -3654,7 +3737,7 @@ msgstr "parametrarna måste registreras i följd a2-a5" msgid "parameters must be registers in sequence r0 to r3" msgstr "parametrarna måste registreras i följd r0-r3" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "pixelkoordinater utanför gränserna" @@ -3678,11 +3761,16 @@ msgstr "pop från en tom PulseIn" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "pop från tom %q" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "port måste vara >= 0" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "pow() 3: e argument kan inte vara 0" @@ -3693,12 +3781,17 @@ msgstr "pow() med 3 argument kräver heltal" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3706,6 +3799,7 @@ msgstr "pow() med 3 argument kräver heltal" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "trycka på startknappen vid start.\n" @@ -3717,13 +3811,21 @@ msgstr "trycka på startknappen vid start.\n" msgid "pressing both buttons at start up.\n" msgstr "trycka båda knapparna vid uppstart.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "håll ner vänster knapp vid start\n" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "pull-mask är i konflikt med riktnings-mask" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" -msgstr "" +msgstr "pull_threshold måste vara mellan 1 och 32" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "push_threshold must be between 1 and 32" -msgstr "" +msgstr "push_threshold måste vara mellan 1 och 32" #: extmod/modutimeq.c msgid "queue overflow" @@ -3733,7 +3835,7 @@ msgstr "köstorlek överskreds" msgid "raw f-strings are not implemented" msgstr "råa f-strängar inte implementerade" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "verkliga och imaginära delar måste ha samma längd" @@ -3768,7 +3870,7 @@ msgstr "rgb_pins[%d] duplicerar en annan pinntilldelning" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins[%d] är inte på samma port som en klocka" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "argumentet roll måste vara en ndarray" @@ -3785,6 +3887,7 @@ msgstr "" "'b' eller 'B'" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "samplingsfrekvens utanför räckvidden" @@ -3816,7 +3919,7 @@ msgstr "tecken tillåts inte med heltalsformatspecificeraren 'c'" msgid "single '}' encountered in format string" msgstr "Enkelt '}' påträffades i formatsträngen" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "storlek är enbart definierad ndarrays" @@ -3840,23 +3943,23 @@ msgstr "värdet för small int överskreds" msgid "soft reboot\n" msgstr "mjuk omstart\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "argumentet sort måste vara en ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "sos array måste ha form (n_section, 6)" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "sos[:, 3] måste vara ettor" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "sosfilt kräver iterable argument" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "källpalett för stor" @@ -3922,7 +4025,7 @@ msgstr "tröskelvärdet måste ligga i intervallet 0-65536" #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "tile must be greater than zero" -msgstr "" +msgstr "tile måste vara större än noll" #: shared-bindings/time/__init__.c msgid "time.struct_time() takes a 9-sequence" @@ -3966,7 +4069,7 @@ msgstr "tobyte kan enbart anropas för täta matriser" msgid "too many arguments provided with the given format" msgstr "för många argument för det givna formatet" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "för många dimensioner" @@ -3979,18 +4082,14 @@ msgstr "för många index" msgid "too many values to unpack (expected %d)" msgstr "för många värden att packa upp (förväntat %d)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "trapz är definierat för 1D-matriser" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "trapz är definierad för 1D-matriser med samma längd" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "triggernivå måste vara 0 eller 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "tupel/lista har fel längd" @@ -4072,7 +4171,7 @@ msgstr "okänd formatkod '%c' för objekt av typ '%q'" msgid "unknown type" msgstr "okänd typ" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "okänd typ '%q'" @@ -4125,14 +4224,6 @@ msgstr "värdet måste passa i %d byte(s)" msgid "value_count must be > 0" msgstr "value_count måste vara > 0" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "vektorer måste ha samma längd" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "wakeup-konflikt" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "watchdog är inte initierad" @@ -4141,6 +4232,11 @@ msgstr "watchdog är inte initierad" msgid "watchdog timeout must be greater than 0" msgstr "watchdog timeout måste vara större än 0" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "width måste vara mellan 2 och 8, inte %d" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "width måste vara större än noll" @@ -4153,7 +4249,7 @@ msgstr "wifi är inte aktiverat" msgid "window must be <= interval" msgstr "window måste vara <= interval" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "fel axelindex" @@ -4161,7 +4257,8 @@ msgstr "fel axelindex" msgid "wrong axis specified" msgstr "fel axel angiven" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "fel indatatyp" @@ -4177,7 +4274,7 @@ msgstr "fel antal värden för att packa upp" msgid "wrong operand type" msgstr "fel operandtyp" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "fel utdatatyp" @@ -4201,18 +4298,148 @@ msgstr "y-värde utanför intervall" msgid "zero step" msgstr "noll steg" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "zi måste vara en ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "zi måste vara av typ float" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "zi måste vara i formen (n_section, 2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper-funktioner stöder för närvarande inte mer än fyra argument" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "adressen %08x är inte justerad till %d byte" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "funktionen tar inte nyckelordsargument" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "parametern annotation måste vara en identifierare" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Total data som ska skrivas är större än outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IO 0, 2 & 4 stöder inte intern pullup för sovläge" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "buffer måste vara en byte-liknande objekt" + +#~ msgid "io must be rtc io" +#~ msgstr "io måste vara rtc io" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "triggernivå måste vara 0 eller 1" + +#~ msgid "wakeup conflict" +#~ msgstr "wakeup-konflikt" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "Försökte tilldela heap när MicroPython VM inte körs." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR jump misslyckades. Troligen korrupt minne." + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython fatalt fel." + +#~ msgid "argument must be ndarray" +#~ msgstr "argument måste vara ndarray" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "matrisdimensioner matchar inte" + +#~ msgid "norm is defined for 1D and 2D arrays" +#~ msgstr "norm är definierad för 1D- och 2D-matriser" + +#~ msgid "vectors must have same lengths" +#~ msgstr "vektorer måste ha samma längd" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Påståendet om Nordic Soft Device-fel." + +#~ msgid "Nordic soft device out of memory" +#~ msgstr "Nordic soft-enheten har slut på minne" + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Okänt mjukvarufel: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "första argumentet måste vara en iterable" + +#~ msgid "iterables are not of the same length" +#~ msgstr "iterables är inte av samma längd" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Vald CTS-pinne är inte giltig" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Vald CTS-pinne är inte giltig" + +#~ msgid "Could not initialize channel" +#~ msgstr "Det gick inte att initiera kanalen" + +#~ msgid "Could not initialize timer" +#~ msgstr "Det gick inte att initialisera timern" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Ogiltig frekvens angiven" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "Ogiltiga pinnar för PWMOut" + +#~ msgid "No more channels available" +#~ msgstr "Inga fler kanaler tillgängliga" + +#~ msgid "No more timers available" +#~ msgstr "Ingen timer tillgänglig" + +#~ msgid "No more timers available on this pin." +#~ msgstr "Inga fler timers tillgängliga på denna pinne." + +#~ msgid "" +#~ "Timer was reserved for internal use - declare PWM pins earlier in the " +#~ "program" +#~ msgstr "" +#~ "Timern är reserverad för internt bruk - deklarera PWM-pinne tidigare i " +#~ "programmet" + +#~ msgid "Group full" +#~ msgstr "Gruppen är full" + +#~ msgid "In buffer elements must be 4 bytes long or less" +#~ msgstr "Inbuffertelement måste vara 4 byte långa eller mindre" + +#~ msgid "Out buffer elements must be 4 bytes long or less" +#~ msgstr "Utbuffertelement ska vara max fyra byte långa" + +#~ msgid "Initial set pin direcion conflicts with initial out pin direction" +#~ msgstr "Initial pinn-riktning står i konflikt med initial utpinn-riktning" + +#~ msgid "UART not yet supported" +#~ msgstr "UART stöds ännu inte" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bits måste vara 7, 8 eller 9" + +#~ msgid "Only IN/OUT of up to 8 supported" +#~ msgstr "Endast IN/OUT på upp till 8 stöds" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA eller SCL behöver en pullup" + +#~ msgid "Invalid use of TLS Socket" +#~ msgstr "Ogiltig användning av TLS Socket" + +#~ msgid "Issue setting SO_REUSEADDR" +#~ msgstr "Misslyckades att sätta SO_REUSEADDR" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "%d adresspinnar och %d RGB-pinnar indikerar en höjd av %d, inte %d" @@ -4397,9 +4624,6 @@ msgstr "zi måste vara i formen (n_section, 2)" #~ msgid "can't convert to float" #~ msgstr "kan inte konvertera till float" -#~ msgid "can't convert to int" -#~ msgstr "kan inte konvertera till int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "objektet '%s' är inte en tupel eller lista" diff --git a/locale/zh_Latn_pinyin.po b/locale/zh_Latn_pinyin.po index 09def433009eb..8062dfe3ee4cf 100644 --- a/locale/zh_Latn_pinyin.po +++ b/locale/zh_Latn_pinyin.po @@ -7,7 +7,7 @@ msgstr "" "Project-Id-Version: circuitpython-cn\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2021-01-30 02:32+0000\n" +"PO-Revision-Date: 2021-04-19 19:15+0000\n" "Last-Translator: hexthat \n" "Language-Team: Chinese Hanyu Pinyin\n" "Language: zh_Latn_pinyin\n" @@ -15,7 +15,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" -"X-Generator: Weblate 4.5-dev\n" +"X-Generator: Weblate 4.7-dev\n" #: main.c msgid "" @@ -83,6 +83,7 @@ msgstr "%q zhèngzài shǐyòng" #: extmod/moductypes.c ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/obj.c py/objstr.c #: py/objstrunicode.c msgid "%q index out of range" @@ -112,6 +113,7 @@ msgstr "%q bìxū dàyú huò děngyú 1" msgid "%q must be a tuple of length 2" msgstr "%q bìxū shì chángdù wèi 2 de yuán zǔ" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #: shared-bindings/canio/Match.c msgid "%q out of range" msgstr "%q chāochū fànwéi" @@ -342,16 +344,21 @@ msgid "All SPI peripherals are in use" msgstr "Suǒyǒu SPI wàiwéi qì zhèngzài shǐyòng" #: ports/esp32s2/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "All UART peripherals are in use" msgstr "Suǒyǒu UART wàiwéi zhèngzài shǐyòng" +#: shared-bindings/pwmio/PWMOut.c +msgid "All channels in use" +msgstr "suǒ yǒu shǐ yòng de tōng dào" + #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" msgstr "Suǒyǒu shǐyòng de shìjiàn píndào" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "All state machines in use" -msgstr "" +msgstr "suǒ yǒu zhèng zài shǐ yòng de zhuàng tài jī" #: ports/atmel-samd/audio_dma.c ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "All sync event channels in use" @@ -373,6 +380,7 @@ msgstr "Cǐ yǐn jiǎo de suǒyǒu jìshí qì zhèngzài shǐyòng" #: ports/esp32s2/common-hal/pulseio/PulseOut.c #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c #: ports/nrf/common-hal/pulseio/PulseIn.c ports/nrf/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c #: ports/stm/peripherals/timers.c shared-bindings/pwmio/PWMOut.c msgid "All timers in use" msgstr "Suǒyǒu jìshí qì shǐyòng" @@ -413,6 +421,10 @@ msgstr "AnalogOut jǐn wèi 16 wèi. Zhí bìxū xiǎoyú 65536." msgid "AnalogOut not supported on given pin" msgstr "Wèi zhīchí zhǐdìng de yǐn jiǎo AnalogOut" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "lìng yí gè PWMAudioOut yǐ jīng chǔ yú huó dòng zhuàng tài" + #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c msgid "Another send is already active" @@ -436,8 +448,8 @@ msgid "Attempt to allocate %d blocks" msgstr "cháng shì fēn pèi %d kuài" #: supervisor/shared/safe_mode.c -msgid "Attempted heap allocation when MicroPython VM not running." -msgstr "MicroPython VM zài wèi yùnxíng shí chángshì fēnpèi duī." +msgid "Attempted heap allocation when VM not running." +msgstr "dāng VM bú yùn xíng shí, cháng shì duī fēn pèi." #: shared-bindings/wifi/Radio.c msgid "Authentication failure" @@ -464,6 +476,10 @@ msgstr "wài shè bù zhī chí de bō tè lā tè" msgid "Below minimum frame rate" msgstr "Dī yú zuìdī zhèng sùlǜ" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +msgid "Bit clock and word select must be sequential pins" +msgstr "wèi shí zhōng hé dān cí xuǎn zé bì xū shì shùn xù yǐn jiǎo" + #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must share a clock unit" msgstr "Bǐtè shízhōng hé dānzì xuǎnzé bìxū gòngxiǎng shízhōng dānwèi" @@ -505,6 +521,10 @@ msgstr "Liàngdù wúfǎ tiáozhěng" msgid "Buffer + offset too small %d %d %d" msgstr "Huǎnchōng qū hé piān yí liàng tài xiǎo %d %d %d" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "huǎn chōng yuán jiàn bì xū wéi 4 zì jié cháng huò gèng shǎo" + #: shared-module/usb_hid/Device.c #, c-format msgid "Buffer incorrect size. Should be %d bytes." @@ -521,6 +541,7 @@ msgid "Buffer is too small" msgstr "Huǎnchōng qū tài xiǎo" #: ports/nrf/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format msgid "Buffer length %d too big. It must be less than %d" msgstr "Huǎnchōng qū chángdù%d tài dà. Tā bìxū xiǎoyú%d" @@ -550,6 +571,7 @@ msgstr "Huǎn chōng qū tài duǎn , àn %d zì jié" #: ports/atmel-samd/common-hal/displayio/ParallelBus.c #: ports/esp32s2/common-hal/displayio/ParallelBus.c #: ports/nrf/common-hal/displayio/ParallelBus.c +#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #, c-format msgid "Bus pin %d is already in use" msgstr "Zǒngxiàn yǐn jiǎo %d yǐ zài shǐyòng zhōng" @@ -643,6 +665,10 @@ msgstr "USB jīhuó shí wúfǎ chóngxīn bǎng ding '/'." msgid "Cannot reset into bootloader because no bootloader is present." msgstr "Wúfǎ chóng zhì wèi bootloader, yīnwèi méiyǒu bootloader cúnzài." +#: ports/esp32s2/common-hal/socketpool/Socket.c +msgid "Cannot set socket options" +msgstr "wú fǎ shè zhì tào jiē zì xuǎn xiàng" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." msgstr "Dāng fāngxiàng xiàng nèi shí, bùnéng shèzhì gāi zhí." @@ -664,7 +690,7 @@ msgstr "Méiyǒu MOSI/MISO jiù wúfǎ zhuǎnyí." msgid "Cannot unambiguously get sizeof scalar" msgstr "Wúfǎ míngquè de huòdé biāoliàng de dàxiǎo" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Cannot vary frequency on a timer that is already in use" msgstr "Wúfǎ gēnggǎi yǐ zài shǐyòng de jìshí qì shàng de pínlǜ" @@ -748,14 +774,6 @@ msgstr "wú fǎ chū shǐ huà SDCard" msgid "Could not initialize UART" msgstr "Wúfǎ chūshǐhuà UART" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize channel" -msgstr "Wúfǎ chūshǐhuà píndào" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c ports/stm/common-hal/pwmio/PWMOut.c -msgid "Could not initialize timer" -msgstr "Wúfǎ chūshǐhuà jìshí qì" - #: ports/stm/common-hal/pwmio/PWMOut.c msgid "Could not re-init channel" msgstr "Wúfǎ chóngxīn chūshǐhuà píndào" @@ -776,7 +794,7 @@ msgstr "Wúfǎ huòqǔ shízhōng" msgid "Could not set address" msgstr "wú fǎ shè zhì dì zhǐ" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Could not start PWM" msgstr "Wúfǎ qǐdòng PWM" @@ -877,11 +895,16 @@ msgstr "ESP-IDF nèicún fēnpèi shībài" msgid "EXTINT channel already in use" msgstr "EXTINT píndào yǐjīng shǐyòng" +#: shared-module/synthio/MidiTrack.c +#, c-format +msgid "Error in MIDI stream at position %d" +msgstr "wèi yú %d wèi zhì de MIDI liú zhōng de cuò wù" + #: extmod/modure.c msgid "Error in regex" msgstr "Zhèngzé biǎodá shì cuòwù" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "Error: Failure to bind" msgstr "cuò wù: bǎng dìng shī bài" @@ -932,15 +955,15 @@ msgstr "Qīwàng de chángdù wèi %d de yuán zǔ, dédào %d" msgid "Extended advertisements with scan response not supported." msgstr "Bù zhīchí dài yǒu sǎomiáo xiǎngyìng de kuòzhǎn guǎngbò." -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is defined for ndarrays only" msgstr "FFT jǐn wéi ndarrays dìng yì" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "FFT is implemented for linear arrays only" msgstr "FFT jǐn shì yòng yú xiàn xìng zhèn liè" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c msgid "Failed SSL handshake" msgstr "SSL wòshǒu shībài" @@ -954,6 +977,7 @@ msgid "Failed to acquire mutex, err 0x%04x" msgstr "Wúfǎ huòdé mutex, err 0x%04x" #: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Failed to allocate RX buffer" msgstr "Fēnpèi RX huǎnchōng shībài" @@ -962,6 +986,7 @@ msgstr "Fēnpèi RX huǎnchōng shībài" #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c #, c-format msgid "Failed to allocate RX buffer of %d bytes" @@ -975,6 +1000,10 @@ msgstr "Wúfǎ fēnpèi Wifi nèicún" msgid "Failed to allocate wifi scan memory" msgstr "Wúfǎ fēnpèi wifi sǎomiáo nèicún" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "wèi néng huǎn chōng yàng běn" + #: ports/nrf/common-hal/_bleio/Adapter.c msgid "Failed to connect: internal error" msgstr "Liánjiē shībài: Nèibù cuòwù" @@ -1000,6 +1029,10 @@ msgstr "Wúfǎ shìfàng mutex, err 0x%04x" msgid "Failed to write internal flash." msgstr "Wúfǎ xiě rù nèibù shǎncún." +#: supervisor/shared/safe_mode.c +msgid "Fatal error." +msgstr "zhì mìng cuò wù." + #: py/moduerrno.c msgid "File exists" msgstr "Wénjiàn cúnzài" @@ -1023,7 +1056,7 @@ msgstr "Bù zhīyuán géshì" msgid "Framebuffer requires %d bytes" msgstr "zhēn huǎn chōng qū xū yào %d zì jié" -#: ports/stm/common-hal/pwmio/PWMOut.c +#: shared-bindings/pwmio/PWMOut.c msgid "Frequency must match existing PWMOut using this timer" msgstr "Pínlǜ bìxū yǔ shǐyòng cǐ jìshí qì de xiàn yǒu PWMOut xiāng pǐpèi" @@ -1042,10 +1075,6 @@ msgstr "tōng yòng gù zhàng" msgid "Group already used" msgstr "Jítuán yǐjīng shǐyòngguò" -#: shared-module/displayio/Group.c -msgid "Group full" -msgstr "Fēnzǔ yǐ mǎn" - #: ports/mimxrt10xx/common-hal/busio/SPI.c ports/stm/common-hal/busio/I2C.c #: ports/stm/common-hal/busio/SPI.c ports/stm/common-hal/canio/CAN.c #: ports/stm/common-hal/sdioio/SDCard.c @@ -1070,21 +1099,21 @@ msgstr "I2C chūshǐhuà cuòwù" #: ports/raspberrypi/common-hal/busio/I2C.c msgid "I2C peripheral in use" -msgstr "" +msgstr "I2C wài shè zhèng zài shǐ yòng zhōng" #: shared-bindings/audiobusio/I2SOut.c msgid "I2SOut not available" msgstr "I2SOut bù kě yòng" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" -msgstr "IOS 0, 2 + 4 bù zhī chí shuì mián zhōng de nèi bù shàng lā" - #: shared-bindings/aesio/aes.c #, c-format msgid "IV must be %d bytes long" msgstr "IV bì xū wéi %d zì jié cháng" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "huǎn chōng nèi yuán sù bì xū <= 4 zì jié cháng" + #: py/persistentcode.c msgid "" "Incompatible .mpy file. Please update all .mpy files. See http://adafru.it/" @@ -1099,12 +1128,30 @@ msgstr "Huǎnchōng qū dàxiǎo bù zhèngquè" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Init program size invalid" +msgstr "Init chéng xù dà xiǎo wú xiào" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" msgstr "" +"chū shǐ shè zhì yǐn jiǎo fāng xiàng yǔ chū shǐ chū yǐn jiǎo fāng xiàng chōng " +"tū" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" +"chū shǐ shè zhì yǐn jiǎo zhuàng tài yǔ chū shǐ chū yǐn jiǎo zhuàng tài chōng " +"tū" #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "Initialization failed due to lack of memory" msgstr "yóu yú nèi cún bù zú, chū shǐ huà shī bài" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "" +"shū rù huǎn chōng qū cháng dù (%d) bì xū shì liàn jì shù de bèi shù (%d)" + #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" msgstr "Shūrù shíjiānguò zhǎng" @@ -1116,27 +1163,27 @@ msgstr "Shūrù/shūchū cuòwù" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d jumps on pin" -msgstr "" +msgstr "zhǐ lìng %d zài yǐn jiǎo shàng tiào zhuǎn" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts in more bits than pin count" -msgstr "" +msgstr "zhǐ lìng %d yí wèi chāo guò yǐn jiǎo jì shù" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts out more bits than pin count" -msgstr "" +msgstr "zhǐ lìng %d yí chū de wèi bǐ yǐn jiǎo shù duō" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d uses extra pin" -msgstr "" +msgstr "zhǐ lìng %d shǐ yòng é wài de yǐn jiǎo" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d waits on input outside of count" -msgstr "" +msgstr "zhǐ lìng %d děng dài jì shù zhī wài de shū rù" #: ports/nrf/common-hal/_bleio/__init__.c msgid "Insufficient authentication" @@ -1161,6 +1208,7 @@ msgstr "wú xiào %q" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/mimxrt10xx/common-hal/busio/UART.c msgid "Invalid %q pin" msgstr "Wúxiào de %q yǐn jiǎo" @@ -1187,8 +1235,14 @@ msgstr "Wúxiào de BSSID" msgid "Invalid DAC pin supplied" msgstr "Tí gōng liǎo wúxiào de DAC yǐn jiǎo" +#: shared-bindings/synthio/__init__.c +msgid "Invalid MIDI file" +msgstr "wú xiào de MIDI wén jiàn" + #: ports/atmel-samd/common-hal/pwmio/PWMOut.c -#: ports/cxd56/common-hal/pwmio/PWMOut.c ports/nrf/common-hal/pwmio/PWMOut.c +#: ports/cxd56/common-hal/pwmio/PWMOut.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/nrf/common-hal/pwmio/PWMOut.c #: ports/raspberrypi/common-hal/pwmio/PWMOut.c shared-bindings/pwmio/PWMOut.c msgid "Invalid PWM frequency" msgstr "Wúxiào de PWM pínlǜ" @@ -1206,7 +1260,8 @@ msgstr "Wúxiào de cānshù" msgid "Invalid bits per value" msgstr "Měi gè zhí de wèi wúxiào" -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "Invalid buffer size" msgstr "Wúxiào de huǎnchōng qū dàxiǎo" @@ -1235,14 +1290,10 @@ msgstr "Wúxiào de wénjiàn" msgid "Invalid format chunk size" msgstr "Géshì kuài dàxiǎo wúxiào" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c +#: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/pwmio/PWMOut.c msgid "Invalid frequency" msgstr "Wúxiào de pínlǜ" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid frequency supplied" -msgstr "Tígōng de pínlǜ wúxiào" - #: supervisor/shared/safe_mode.c msgid "Invalid memory access." msgstr "Wúxiào de nèicún fǎngwèn." @@ -1281,17 +1332,13 @@ msgstr "Yòuxián tōngdào yǐn jiǎo wúxiào" #: ports/esp32s2/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/SPI.c #: ports/esp32s2/common-hal/busio/UART.c ports/esp32s2/common-hal/canio/CAN.c #: ports/mimxrt10xx/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/SPI.c +#: ports/raspberrypi/common-hal/busio/UART.c msgid "Invalid pins" msgstr "Wúxiào de yǐn jiǎo" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "Invalid pins for PWMOut" -msgstr "PWMOut de yǐn jiǎo wú xiào" - #: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c #: shared-bindings/displayio/FourWire.c msgid "Invalid polarity" @@ -1313,7 +1360,7 @@ msgstr "Ānquán móshì wúxiào" msgid "Invalid size" msgstr "dà xiǎo wú xiào" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLContext.c msgid "Invalid socket for TLS" msgstr "TLS de chā zuò wú xiào" @@ -1321,10 +1368,6 @@ msgstr "TLS de chā zuò wú xiào" msgid "Invalid state" msgstr "wú xiào zhuàng tài" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Invalid use of TLS Socket" -msgstr "TLS tào jiē zì de wú xiào shǐ yòng" - #: shared-bindings/audiomixer/Mixer.c msgid "Invalid voice" msgstr "Yǔyīn wúxiào" @@ -1337,14 +1380,11 @@ msgstr "Wúxiào de yǔyīn jìshù" msgid "Invalid wave file" msgstr "Wúxiào de làng làngcháo wénjiàn" -#: ports/stm/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "Invalid word/bit length" msgstr "Wúxiào de zì/wèi chángdù" -#: ports/esp32s2/common-hal/socketpool/Socket.c -msgid "Issue setting SO_REUSEADDR" -msgstr "wèn tí shè zhì SO_REUSEADDR" - #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" msgstr "mì yào bì xū wéi 16, 24 huò 32 zì jié cháng" @@ -1390,14 +1430,6 @@ msgstr "Jìngxiàng shí de zuìdà X zhí wèi%d" msgid "Messages limited to 8 bytes" msgstr "Yóujiàn xiànzhì wèi 8 gè zì jié" -#: supervisor/shared/safe_mode.c -msgid "MicroPython NLR jump failed. Likely memory corruption." -msgstr "MicroPython NLR tiào zhuǎn shībài. Kěnéng shì nèicún sǔnhuài." - -#: supervisor/shared/safe_mode.c -msgid "MicroPython fatal error." -msgstr "MicroPython zhìmìng cuòwù." - #: shared-bindings/audiobusio/PDMIn.c msgid "Microphone startup delay must be in range 0.0 to 1.0" msgstr "Màikèfēng qǐdòng yánchí bìxū zài 0.0 Dào 1.0 De fànwéi nèi" @@ -1409,32 +1441,33 @@ msgstr "Quēshǎo MISO huò MOSI yǐn jiǎo" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d reads pin(s)" -msgstr "" +msgstr "shǒu xiān zài yǐn jiǎo zhōng quē shī. zhǐ lìng %d dú qǔ yǐn jiǎo" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d shifts in from pin(s)" -msgstr "" +msgstr "shǒu xiān zài yǐn jiǎo zhōng quē shī. zhǐ lìng %d cóng yǐn jiǎo yí wèi" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_in_pin. Instruction %d waits based on pin" msgstr "" +"shǒu xiān zài yǐn jiǎo zhōng quē shī. jī yú yǐn jiǎo de zhǐ lìng %d děng dài" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d shifts out to pin(s)" -msgstr "" +msgstr "xiān lòu chū yǐn jiǎo. zhǐ lìng %d yí chū dào yǐn jiǎo" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_out_pin. Instruction %d writes pin(s)" -msgstr "" +msgstr "xiān lòu chū yǐn jiǎo. zhǐ lìng %d xiě rù yǐn jiǎo" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Missing first_set_pin. Instruction %d sets pin(s)" -msgstr "" +msgstr "quē shǎo dì yī zǔ yǐn jiǎo. zhǐ lìng %d shè zhì yǐn jiǎo" #: shared-bindings/displayio/Group.c msgid "Must be a %q subclass." @@ -1449,6 +1482,10 @@ msgstr "Bìxū tígōng MISO huò MOSI yǐn jiǎo" msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "bì xū shǐ yòng 6 RGB yǐn jiǎo de bèi shù, ér bù shì %d" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "NLR tiào zhuǎn shī bài. kě néng shì nèi cún sǔn huài." + #: ports/esp32s2/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS cuò wù" @@ -1468,9 +1505,15 @@ msgstr "Méiyǒu DAC zài xīnpiàn shàng de" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA channel found" msgstr "Wèi zhǎodào DMA píndào" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "wèi zhǎo dào DMA qǐ bó qì" + #: shared-module/adafruit_bus_device/I2CDevice.c #, c-format msgid "No I2C device at address: %x" @@ -1529,6 +1572,14 @@ msgstr "Shízhōng yǐn jiǎo wú yìngjiàn zhīchí" msgid "No hardware support on pin" msgstr "Méiyǒu zài yǐn jiǎo shàng de yìngjiàn zhīchí" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "chéng xù zhōng méi yǒu" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "chéng xù zhōng méi yǒu jìn chū" + #: shared-bindings/aesio/aes.c msgid "No key was specified" msgstr "Wèi zhǐdìng mì yào" @@ -1537,25 +1588,19 @@ msgstr "Wèi zhǐdìng mì yào" msgid "No long integer support" msgstr "Méiyǒu zhǎng zhěngshù zhīchí" -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more channels available" -msgstr "Méiyǒu gèng duō kěyòng píndào" - -#: ports/esp32s2/common-hal/pwmio/PWMOut.c -msgid "No more timers available" -msgstr "Méiyǒu gèng duō kěyòng de jìshí qì" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "No more timers available on this pin." -msgstr "Gāi yǐn jiǎo shàng méiyǒu kěyòng de dìngshí qì." - #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" msgstr "Méiyǒu wǎngluò yǔ gāi ssid" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No out in program" -msgstr "" +msgstr "chéng xù zhōng wèi tuì chū" + +#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/busio/I2C.c +msgid "No pull up found on SDA or SCL; check your wiring" +msgstr "zài SDA huò SCL shàng wèi zhǎo dào shàng lā; jiǎn chá nín de xiàn lù" #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" @@ -1574,13 +1619,18 @@ msgid "No timer available" msgstr "Méiyǒu jìshí qì" #: supervisor/shared/safe_mode.c -msgid "Nordic Soft Device failure assertion." -msgstr "Nordic ruǎn shèbèi gùzhàng shēngmíng." +msgid "Nordic system firmware failure assertion." +msgstr "běi ōu xì tǒng gù jiàn gù zhàng duàn yán." + +#: ports/nrf/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "běi ōu xì tǒng gù jiàn chū nèi cún" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" msgstr "Wúxiào de IP zìfú chuàn" +#: ports/nrf/common-hal/_bleio/PacketBuffer.c #: ports/nrf/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c msgid "Not connected" @@ -1610,13 +1660,10 @@ msgid "Odd parity is not supported" msgstr "Bù zhīchí jīshù" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "Only 8 or 16 bit mono with " msgstr "Zhǐyǒu 8 huò 16 wèi dānwèi " -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Only IN/OUT of up to 8 supported" -msgstr "" - #: ports/esp32s2/common-hal/wifi/__init__.c msgid "Only IPv4 addresses supported" msgstr "Jǐn zhīchí IPv4 dìzhǐ" @@ -1670,10 +1717,19 @@ msgstr "cāo zuò yǐ fēn shí" msgid "Out of memory" msgstr "nèi cún bù zú" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/socketpool/SocketPool.c msgid "Out of sockets" msgstr "tào jiē zì wài" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "huǎn chōng wài yuán sù bì xū <= 4 zì jié cháng" + +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Output buffer must be at least %d bytes" +msgstr "shū chū huǎn chōng qū bì xū zhì shǎo wéi %d zì jié" + #: shared-bindings/audiobusio/PDMIn.c msgid "Oversample must be multiple of 8." msgstr "Guò cǎiyàng bìxū shì 8 de bèishù." @@ -1693,8 +1749,15 @@ msgid "" "PWM frequency not writable when variable_frequency is False on construction." msgstr "Dāng biànliàng_pínlǜ shì False zài jiànzhú shí PWM pínlǜ bùkě xiě." +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "yǐ jīng zài shǐ yòng de PWM qiē piàn" + +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "PWM qiē piàn tōng dào A yǐ zài shǐ yòng zhōng" + #: ports/mimxrt10xx/common-hal/displayio/ParallelBus.c -#: ports/raspberrypi/common-hal/displayio/ParallelBus.c #: ports/stm/common-hal/displayio/ParallelBus.c msgid "ParallelBus not yet supported" msgstr "Shàng bù zhīchí ParallelBus" @@ -1709,11 +1772,11 @@ msgstr "Quánxiàn bèi jùjué" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Pin count must be at least 1" -msgstr "" +msgstr "yǐn jiǎo jì shù bì xū zhì shǎo wéi 1" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Pin count too large" -msgstr "" +msgstr "yǐn jiǎo jì shù tài dà" #: ports/atmel-samd/common-hal/analogio/AnalogIn.c #: ports/cxd56/common-hal/analogio/AnalogIn.c @@ -1730,6 +1793,10 @@ msgstr "Pin méiyǒu ADC nénglì" msgid "Pin is input only" msgstr "Yǐn jiǎo jǐn shūrù" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "yǐn jiǎo bì xū zài Pwm pín dào B shàng" + #: ports/atmel-samd/common-hal/countio/Counter.c msgid "Pin must support hardware interrupts" msgstr "Yǐn jiǎo bìxū zhīchí yìngjiàn zhōngduàn" @@ -1749,6 +1816,14 @@ msgstr "" "duōzì jié. Rúguǒ wúfǎ bìmiǎn, qǐng jiāng allow_inefficient = True chuándì " "gěigòuzào hánshù" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential" +msgstr "yǐn jiǎo bì xū shì lián xù de" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "yǐn jiǎo bì xū gòng xiǎng PWM qiē piàn" + #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" msgstr "Zài wénjiàn xìtǒng shàng tiānjiā rènhé mókuài\n" @@ -1789,23 +1864,23 @@ msgstr "" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does IN without loading ISR" -msgstr "" +msgstr "chéng xù zài bù jiā zǎi ISR de qíng kuàng xià wán chéng" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does OUT without loading OSR" -msgstr "" +msgstr "chéng xù zài bù jiā zǎi Osr de qíng kuàng xià zhí xíng OUT" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program must contain at least one 16-bit instruction." -msgstr "" +msgstr "chéng xù bì xū zhì shǎo bāo hán yí gè 16 wèi zhǐ lìng ." #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program size invalid" -msgstr "" +msgstr "chéng xù dà xiǎo wú xiào" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Program too large" -msgstr "" +msgstr "chéng xù tài dà" #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." @@ -1813,7 +1888,7 @@ msgstr "Fāngxiàng shūchū shí Pull méiyǒu shǐyòng." #: ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c msgid "RAISE mode is not implemented" -msgstr "" +msgstr "wèi shí xiàn tí shēng mó shì" #: ports/stm/common-hal/os/__init__.c msgid "RNG DeInit Error" @@ -1823,6 +1898,10 @@ msgstr "RNG qǔxiāo chūshǐhuà cuòwù" msgid "RNG Init Error" msgstr "RNG chūshǐhuà cuòwù" +#: ports/nrf/common-hal/busio/UART.c ports/raspberrypi/common-hal/busio/UART.c +msgid "RS485 Not yet supported on this device" +msgstr "RS485 cǐ shè bèi shàng bù zhī chí" + #: ports/esp32s2/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c msgid "RS485 inversion specified when not in RS485 mode" @@ -1830,6 +1909,7 @@ msgstr "Wèi chǔyú RS485 móshì shí zhǐdìngle RS485 fǎn zhuǎn" #: ports/cxd56/common-hal/rtc/RTC.c ports/esp32s2/common-hal/rtc/RTC.c #: ports/mimxrt10xx/common-hal/rtc/RTC.c ports/nrf/common-hal/rtc/RTC.c +#: ports/raspberrypi/common-hal/rtc/RTC.c msgid "RTC calibration is not supported on this board" msgstr "Cǐ bǎn bù zhīchí RTC jiàozhǔn" @@ -1838,7 +1918,7 @@ msgid "RTC is not supported on this board" msgstr "Cǐ bǎn bù zhīchí RTC" #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nrf/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c msgid "RTS/CTS/RS485 Not yet supported on this device" msgstr "RTS/CTS/RS485 gāi shèbèi shàng bù zhīchí" @@ -1895,12 +1975,6 @@ msgstr "Zài ānquán móshì xià yùnxíng! " msgid "SD card CSD format not supported" msgstr "Bù zhīchí SD kǎ CSD géshì" -#: ports/atmel-samd/common-hal/busio/I2C.c ports/esp32s2/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nrf/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "SDA or SCL needs a pull up" -msgstr "SDA huò SCL xūyào lādòng" - #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" @@ -1921,7 +1995,7 @@ msgstr "SPI chóngxīn chūshǐhuà cuòwù" #: ports/raspberrypi/common-hal/busio/SPI.c msgid "SPI peripheral in use" -msgstr "" +msgstr "SPI wài shè zhèng zài shǐ yòng zhōng" #: shared-bindings/audiomixer/Mixer.c msgid "Sample rate must be positive" @@ -1936,14 +2010,6 @@ msgstr "Cǎiyàng lǜ tài gāo. Tā bìxū xiǎoyú %d" msgid "Scan already in progess. Stop with stop_scan." msgstr "Zhèngzài jìn háng sǎomiáo. Shǐyòng stop_scan tíngzhǐ." -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected CTS pin not valid" -msgstr "Suǒ xuǎn de CTS yǐn jiǎo wúxiào" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Selected RTS pin not valid" -msgstr "Suǒ xuǎn de RTS yǐn jiǎo wúxiào" - #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c msgid "Serializer in use" @@ -1955,11 +2021,11 @@ msgstr "Fúwùqì duān shàngxiàwén bùnéng jùyǒu zhǔjī míng" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Set pin count must be between 1 and 5" -msgstr "" +msgstr "shè zhì yǐn jiǎo shù bì xū jiè yú 1 hé 5 zhī jiān" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Side set pin count must be between 1 and 5" -msgstr "" +msgstr "cè miàn shè zhì yǐn jiǎo shù bì xū jiè yú 1 hé 5 zhī jiān" #: ports/cxd56/common-hal/camera/Camera.c msgid "Size not supported" @@ -1992,6 +2058,14 @@ msgstr "Yǔ zi bǔhuò fēnliè" msgid "Stack size must be at least 256" msgstr "Duīzhàn dàxiǎo bìxū zhìshǎo 256" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo left must be on PWM channel A" +msgstr "lì tǐ shēng zuǒ bì xū shì zài PWM tōng dào A" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Stereo right must be on PWM channel B" +msgstr "lì tǐ shēng yòu cè bì xū zài PWM tōng dào B shàng" + #: shared-bindings/multiterminal/__init__.c msgid "Stream missing readinto() or write() method." msgstr "Liú quēshǎo readinto() huò write() fāngfǎ." @@ -2083,18 +2157,12 @@ msgstr "shí jiān yǐ jīng guò qù." msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "Chāoshí shíjiān tài zhǎng: Zuìdà chāoshí shíjiān wèi%d miǎo" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "" -"Timer was reserved for internal use - declare PWM pins earlier in the program" -msgstr "" -"Dìngshí qì bǎoliú gōng nèibù shǐyòng-zài chéngxù de qiánmiàn shēngmíng PWM " -"yǐn jiǎo" - #: supervisor/shared/safe_mode.c msgid "To exit, please reset the board without " msgstr "Yào tuìchū, qǐng chóng zhì bǎnkuài ér bùyòng " #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." msgstr "Chōuyàng zhōng de píndào tài duō." @@ -2107,8 +2175,8 @@ msgid "Too many displays" msgstr "Xiǎnshì tài duō" #: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than outgoing_packet_length" -msgstr "Yào xiě rù de zǒng shùjù dàyú outgoing_packet_length" +msgid "Total data to write is larger than %q" +msgstr "" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2134,10 +2202,6 @@ msgstr "UART chūshǐhuà cuòwù" msgid "UART Re-init error" msgstr "UART chóngxīn chūshǐhuà cuòwù" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART not yet supported" -msgstr "" - #: ports/stm/common-hal/busio/UART.c msgid "UART write error" msgstr "UART xiě cuòwù" @@ -2164,6 +2228,8 @@ msgstr "UUID zhí bùshì str,int huò zì jié huǎnchōng qū" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c #: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Unable to allocate buffers for signed conversion" msgstr "Wúfǎ fēnpèi huǎnchōng qū yòng yú qiānmíng zhuǎnhuàn" @@ -2201,7 +2267,7 @@ msgstr "wú fǎ xiě rù sleep_memory。" msgid "Unexpected nrfx uuid type" msgstr "Yìwài de nrfx uuid lèixíng" -#: ports/esp32s2/common-hal/socketpool/Socket.c +#: ports/esp32s2/common-hal/ssl/SSLSocket.c #, c-format msgid "Unhandled ESP TLS error %d %d %x %d" msgstr "Wèi chǔlǐ de ESP TLS cuòwù %d %d %x %d" @@ -2227,8 +2293,8 @@ msgstr "Wèizhī de ānquán cuòwù: 0x%04x" #: ports/nrf/common-hal/_bleio/__init__.c #, c-format -msgid "Unknown soft device error: %04x" -msgstr "Wèizhī de ruǎn shèbèi cuòwù: %04x" +msgid "Unknown system firmware error: %04x" +msgstr "wèi zhī xì tǒng gù jiàn cuò wù: %04x" #: shared-bindings/_pixelbuf/PixelBuf.c #, c-format @@ -2257,7 +2323,7 @@ msgstr "Bù zhīchí de gōnggòng qìchē lèixíng" msgid "Unsupported format" msgstr "Bù zhīchí de géshì" -#: py/moduerrno.c +#: ports/raspberrypi/common-hal/pulseio/PulseOut.c py/moduerrno.c msgid "Unsupported operation" msgstr "Bù zhīchí de cāozuò" @@ -2283,10 +2349,6 @@ msgstr "Zhí chángdù > zuìdà chángdù" msgid "Version was invalid" msgstr "bǎn běn wú xiào" -#: py/emitnative.c -msgid "Viper functions don't currently support more than 4 arguments" -msgstr "Viper hánshù mùqián bù zhīchí chāoguò 4 gè cānshù" - #: ports/stm/common-hal/microcontroller/Processor.c msgid "Voltage read timed out" msgstr "Diànyā dòu qǔ chāoshí" @@ -2373,11 +2435,6 @@ msgstr "xūyào yīgè zì jié lèi duìxiàng" msgid "abort() called" msgstr "zhōngzhǐ () diàoyòng" -#: extmod/machine_mem.c -#, c-format -msgid "address %08x is not aligned to %d bytes" -msgstr "wèi zhǐ %08x wèi yǔ %d wèi yuán zǔ duìqí" - #: shared-bindings/i2cperipheral/I2CPeripheral.c msgid "address out of bounds" msgstr "dìzhǐ chāochū biānjiè" @@ -2386,15 +2443,19 @@ msgstr "dìzhǐ chāochū biānjiè" msgid "addresses is empty" msgstr "dìzhǐ wèi kōng" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "" + #: py/modbuiltins.c msgid "arg is an empty sequence" msgstr "cānshù shì yīgè kōng de xùliè" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort argument must be an ndarray" msgstr "argsort cānshù bìxū shì ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "argsort is not implemented for flattened arrays" msgstr "wèi wéi pīn hé shù zǔ shí xiàn argsort" @@ -2402,10 +2463,6 @@ msgstr "wèi wéi pīn hé shù zǔ shí xiàn argsort" msgid "argument has wrong type" msgstr "cānshù lèixíng cuòwù" -#: extmod/ulab/code/linalg/linalg.c -msgid "argument must be ndarray" -msgstr "Cānshù bìxū shì ndarray" - #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c msgid "argument num/types mismatch" @@ -2415,7 +2472,8 @@ msgstr "cānshù biānhào/lèixíng bù pǐpèi" msgid "argument should be a '%q' not a '%q'" msgstr "cānshù yīnggāi shì '%q', 'bùshì '%q'" -#: extmod/ulab/code/linalg/linalg.c extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c +#: extmod/ulab/code/numpy/transform/transform.c msgid "arguments must be ndarrays" msgstr "cānshù bìxū shì ndarrays" @@ -2428,11 +2486,11 @@ msgstr "shù zǔ hé suǒ yǐn cháng dù bì xū xiāng děng" msgid "array/bytes required on right side" msgstr "yòu cè xūyào shùzǔ/zì jié" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "cháng shì huò qǔ (arg) zuì xiǎo zhí /(arg) zuì dà kōng xù liè" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" msgstr "chángshì huòqǔ kōng xùliè de argmin/ argmax" @@ -2440,15 +2498,15 @@ msgstr "chángshì huòqǔ kōng xùliè de argmin/ argmax" msgid "attributes not supported yet" msgstr "shǔxìng shàngwèi zhīchí" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis is out of bounds" msgstr "zhóu chāo chū biān jiè" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" msgstr "zhóu bì xū wéi \" wú \" huò zhěng shù" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "axis too long" msgstr "zhóu tài cháng" @@ -2473,8 +2531,8 @@ msgid "binary op %q not implemented" msgstr "èrjìnzhì bǎn qián bǎn %q wèi zhíxíng" #: shared-bindings/busio/UART.c -msgid "bits must be 7, 8 or 9" -msgstr "bǐtè bìxū shì 7,8 huò 9" +msgid "bits must be in range 5 to 9" +msgstr "wèi bì xū zài fàn wéi nèi 5 zhì 9" #: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" @@ -2484,15 +2542,11 @@ msgstr "měi jiàn yàngběn bìxū wèi 8 huò 16" msgid "branch not in range" msgstr "fēnzhī bùzài fànwéi nèi" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" msgstr "huǎn chōng qū xiǎo yú qǐng qiú de dà xiǎo" -#: shared-bindings/audiocore/RawSample.c -msgid "buffer must be a bytes-like object" -msgstr "huǎnchōng qū bìxū shì zì jié lèi duìxiàng" - -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" msgstr "huǎn chōng qū dà xiǎo bì xū shì yuán sù dà xiǎo de bèi shù" @@ -2509,7 +2563,7 @@ msgstr "huǎnchōng qū qiēpiàn bìxū chángdù xiāngděng" msgid "buffer too small" msgstr "huǎnchōng qū tài xiǎo" -#: shared-bindings/socketpool/Socket.c +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" msgstr "huǎn chōng qū tài xiǎo, duì yú qǐng qiú de zì jié" @@ -2575,6 +2629,10 @@ msgstr "bùnéng fēnpèi dào biǎodá shì" msgid "can't convert %q to %q" msgstr "Wúfǎ jiāng %q zhuǎnhuàn wèi %q" +#: py/runtime.c +msgid "can't convert %q to int" +msgstr "" + #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" msgstr "wúfǎ jiāng '%q' duìxiàng zhuǎnhuàn wèi %q yǐn hán" @@ -2583,6 +2641,10 @@ msgstr "wúfǎ jiāng '%q' duìxiàng zhuǎnhuàn wèi %q yǐn hán" msgid "can't convert to %q" msgstr "wúfǎ zhuǎnhuàn wèi %q" +#: py/runtime.c +msgid "can't convert to int" +msgstr "bùnéng zhuǎnhuàn wèi int" + #: py/objstr.c msgid "can't convert to str implicitly" msgstr "bùnéng mò shì zhuǎnhuàn wèi str" @@ -2702,6 +2764,10 @@ msgstr "chr() cān shǔ bùzài fànwéi (256)" msgid "circle can only be registered in one parent" msgstr "quānzi zhǐ néng zài yī wèi jiāzhǎng zhōng zhùcè" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "jiá dian bì xū shì (x,y) kuài" + #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" msgstr "dài mǎ chāo chū fàn wéi 0~127" @@ -2749,19 +2815,19 @@ msgstr "chángshù bìxū shì yīgè zhěngshù" msgid "conversion to object" msgstr "zhuǎnhuàn wèi duìxiàng" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be linear arrays" msgstr "juàn jī cānshù bìxū shì xiànxìng shùzǔ" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must be ndarrays" msgstr "juàn jī cānshù bìxū shì ndarrays" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/numpy/filter/filter.c msgid "convolve arguments must not be empty" msgstr "juàn jī cān shǔ bùnéng wéi kōng" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "could not invert Vandermonde matrix" msgstr "wúfǎ fǎn zhuǎn fàndéméng dé jǔzhèn" @@ -2769,15 +2835,15 @@ msgstr "wúfǎ fǎn zhuǎn fàndéméng dé jǔzhèn" msgid "couldn't determine SD card version" msgstr "wúfǎ quèdìng SD kǎ bǎnběn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "cross is defined for 1D arrays of length 3" msgstr "duì yú cháng dù wéi 3 de 1D shù zǔ dìng yì cross" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" msgstr "shùjù bìxū shì kě diédài de" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" msgstr "shùjù chángdù bìxū xiāngděng" @@ -2816,14 +2882,18 @@ msgstr "mùbiāo chángdù bìxū shì > = 0 de zhěngshù" msgid "dict update sequence has wrong length" msgstr "yǔfǎ gēngxīn xùliè de chángdù cuòwù" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "diff argument must be an ndarray" msgstr "bùtóng de cānshù bìxū shì ndarray" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "differentiation order out of range" msgstr "chā yì shùn xù fàn wéi" +#: extmod/ulab/code/numpy/transform/transform.c +msgid "dimensions do not match" +msgstr "chǐ cùn bù pǐ pèi" + #: py/modmath.c py/objfloat.c py/objint_longlong.c py/objint_mpz.c py/runtime.c #: shared-bindings/math/__init__.c msgid "division by zero" @@ -2931,7 +3001,7 @@ msgid "f-string: single '}' is not allowed" msgstr "f-string: bù yǔnxǔ shǐyòng dāngè '}'" #: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c +#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/synthio/__init__.c msgid "file must be a file opened in byte mode" msgstr "wénjiàn bìxū shì zài zì jié móshì xià dǎkāi de wénjiàn" @@ -2939,11 +3009,11 @@ msgstr "wénjiàn bìxū shì zài zì jié móshì xià dǎkāi de wénjiàn" msgid "filesystem must provide mount method" msgstr "wénjiàn xìtǒng bìxū tígōng guà zài fāngfǎ" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be a callable" msgstr "dì yī gè cānshù bìxū shì kě tiáo yòng de" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" msgstr "dì yīgè cānshù bìxū shì yī gè hánshù" @@ -2951,11 +3021,7 @@ msgstr "dì yīgè cānshù bìxū shì yī gè hánshù" msgid "first argument must be a tuple of ndarrays" msgstr "dì yī gè cān shù bì xū shì yí gè yuán zǔ ndarrays" -#: extmod/ulab/code/ndarray.c -msgid "first argument must be an iterable" -msgstr "dì yī gè cānshù bìxū shì kě diédài de" - -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "first argument must be an ndarray" msgstr "dì yī gè cānshù bìxū shì ndarray" @@ -2967,7 +3033,7 @@ msgstr "chāojí () de dì yī gè cānshù bìxū shì lèixíng" msgid "flattening order must be either 'C', or 'F'" msgstr "īnhé shùnxù bìxū wèi 'C' huò 'F'" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "flip argument must be an ndarray" msgstr "fānzhuǎn shēn shù bìxū shì ndarray" @@ -2988,8 +3054,8 @@ msgid "full" msgstr "chōngfèn" #: py/argcheck.c -msgid "function does not take keyword arguments" -msgstr "hánshù méiyǒu guānjiàn cí cānshù" +msgid "function doesn't take keyword arguments" +msgstr "" #: py/argcheck.c #, c-format @@ -3000,7 +3066,7 @@ msgstr "hánshù yùjì zuìduō %d cānshù, huòdé %d" msgid "function got multiple values for argument '%q'" msgstr "hánshù huòdé cānshù '%q' de duōchóng zhí" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" msgstr "hánshù zài jiàngé mòwěi jùyǒu xiāngtóng de fúhào" @@ -3043,6 +3109,10 @@ msgstr "shēngchéng qì yǐjīng zhíxíng" msgid "generator ignored GeneratorExit" msgstr "shēngchéng qì hūlüè shēngchéng qì tuìchū" +#: py/objgenerator.c +msgid "generator raised StopIteration" +msgstr "" + #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" msgstr "túxíng bìxū wèi 2048 zì jié" @@ -3075,8 +3145,9 @@ msgstr "bù zhèngquè de tiánchōng" msgid "index is out of bounds" msgstr "suǒyǐn chāochū fànwéi" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c extmod/ulab/code/ulab_tools.c #: ports/esp32s2/common-hal/pulseio/PulseIn.c py/obj.c +#: shared-bindings/bitmaptools/__init__.c msgid "index out of range" msgstr "suǒyǐn chāochū fànwéi" @@ -3088,7 +3159,7 @@ msgstr "suǒyǐn bìxū shì zhěngshù" msgid "indices must be integers, slices, or Boolean lists" msgstr "suǒyǐn bìxū shì zhěngshù, qiēpiàn huò bù'ěr zhí lièbiǎo" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" msgstr "chūshǐ zhí bìxū shì kě diédài de" @@ -3108,7 +3179,7 @@ msgstr "shū rù hé shū chū xíng zhuàng bù jiān róng" msgid "input argument must be an integer, a tuple, or a list" msgstr "shū rù cān shù bì xū shì zhěng shù, yuán zǔ huò liè biǎo" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" msgstr "shūrù shùzǔ de chángdù bìxū shì 2 de mì" @@ -3116,15 +3187,15 @@ msgstr "shūrù shùzǔ de chángdù bìxū shì 2 de mì" msgid "input arrays are not compatible" msgstr "shū rù shù zǔ bù jiān róng" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input data must be an iterable" msgstr "shūrù shùjù bìxū shì kě diédài de" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" msgstr "shūrù jǔzhèn bù duìchèn" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is singular" msgstr "shūrù jǔzhèn shì qíyì de" @@ -3140,23 +3211,23 @@ msgstr "shū rù bì xū shì děng jí 2 de zhāng liàng" msgid "input must be an ndarray" msgstr "shū rù bì xū shì ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" msgstr "shū rù bì xū shì yì wéi de" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" msgstr "shūrù bìxū wèi fāng jǔzhèn" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "input must be tuple, list, range, or ndarray" msgstr "shūrù bìxū shì yuán zǔ, lièbiǎo, fànwéi huò ndarray" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "input vectors must be of equal length" msgstr "shūrù xiàngliàng de chángdù bìxū xiāngděng" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "inputs are not iterable" msgstr "shū rù bù kě yí dòng" @@ -3168,7 +3239,7 @@ msgstr "zhěngshù() cānshù 2 bìxū > = 2 qiě <= 36" msgid "integer required" msgstr "xūyào zhěngshù" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "interp is defined for 1D arrays of equal length" msgstr "interp shì wèi děng zhǎng de 1D shùzǔ dìngyì de" @@ -3181,14 +3252,33 @@ msgstr "Jiàngé bìxū zài %s-%s fànwéi nèi" msgid "invalid arguments" msgstr "wúxiào de cānshù" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32" +msgstr "wú xiào bits_per_pixel %d, bì xū shì, 1, 4, 8, 16, 24, huò 32" + #: extmod/modussl_axtls.c msgid "invalid cert" msgstr "zhèngshū wúxiào" +#: py/compile.c +msgid "invalid decorator" +msgstr "wú xiào zhuāng shì" + #: extmod/uos_dupterm.c msgid "invalid dupterm index" msgstr "dupterm suǒyǐn wúxiào" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" +msgstr "wú xiào yuán jiàn dà xiǎo %d wéi bits_per_pixel %d\n" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "wú xiào element_size %d, bì xū shì, 1, 2, huò 4" + #: extmod/modframebuf.c msgid "invalid format" msgstr "wúxiào géshì" @@ -3230,10 +3320,6 @@ msgstr "jīshù wèi %d de zhěng shǔ de yǔfǎ wúxiào" msgid "invalid syntax for number" msgstr "wúxiào de hàomǎ yǔfǎ" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "io must be rtc io" -msgstr "IO bì xū shì RTC IO" - #: py/objtype.c msgid "issubclass() arg 1 must be a class" msgstr "issubclass() cānshù 1 bìxū shì yīgè lèi" @@ -3242,11 +3328,7 @@ msgstr "issubclass() cānshù 1 bìxū shì yīgè lèi" msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "issubclass() cānshù 2 bìxū shì lèi de lèi huò yuán zǔ" -#: extmod/ulab/code/ndarray.c -msgid "iterables are not of the same length" -msgstr "kě diédài xiàng de chángdù bùtóng" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" msgstr "diédài méiyǒu shōuliǎn" @@ -3315,11 +3397,7 @@ msgstr "dìtú huǎnchōng qū tài xiǎo" msgid "math domain error" msgstr "shùxué yù cuòwù" -#: extmod/ulab/code/linalg/linalg.c -msgid "matrix dimensions do not match" -msgstr "jǔzhèn chǐcùn bù pǐpèi" - -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" msgstr "jǔzhèn bùshì zhèngdìng de" @@ -3341,15 +3419,15 @@ msgstr "zuì dà chǐ cùn shù wéi 4" msgid "maximum recursion depth exceeded" msgstr "chāochū zuìdà dìguī shēndù" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" msgstr "maxiter bì xū > 0" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" msgstr "maxiter yìng wéi > 0" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "median argument must be an ndarray" msgstr "zhōng wèi shù cān shù bì xū shì ndarray" @@ -3362,11 +3440,15 @@ msgstr "nèicún fēnpèi shībài, fēnpèi %u zì jié" msgid "memory allocation failed, heap is locked" msgstr "jìyì tǐ fēnpèi shībài, duī bèi suǒdìng" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "nèi cún shì tú: cháng dù bú shì xiàng mù huà de bèi shù" + #: py/builtinimport.c msgid "module not found" msgstr "zhǎo bù dào mókuài" -#: extmod/ulab/code/poly/poly.c +#: extmod/ulab/code/numpy/poly/poly.c msgid "more degrees of freedom than data points" msgstr "bǐ shùjù diǎn gèng duō de zìyóu dù" @@ -3411,6 +3493,10 @@ msgstr "yuán chǎn" msgid "need more than %d values to unpack" msgstr "xūyào chāoguò%d de zhí cáinéng jiědú" +#: py/modmath.c +msgid "negative factorial" +msgstr "" + #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" msgstr "méiyǒu fú diǎn zhīchí de xiāojí gōnglǜ" @@ -3484,10 +3570,6 @@ msgstr "fēi líng chāo shí bì xū > 0.01" msgid "non-zero timeout must be >= interval" msgstr "fēi líng chāo shí bì xū wéi >= jiàn gé" -#: extmod/ulab/code/linalg/linalg.c -msgid "norm is defined for 1D and 2D arrays" -msgstr "wéi 1D hé 2D shù zǔ dìng yì guī fàn" - #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" msgstr "bùshì 128 wèi UUID" @@ -3556,7 +3638,7 @@ msgstr "xūyào huǎnchōng qū xiéyì de duìxiàng" msgid "odd-length string" msgstr "jīshù zìfú chuàn" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ulab_create.c extmod/ulab/code/utils/utils.c msgid "offset is too large" msgstr "piān yí tài dà" @@ -3585,8 +3667,8 @@ msgstr "Jǐn zhīchí cǎiyàng lǜ = 16000" msgid "only slices with step=1 (aka None) are supported" msgstr "jǐn zhīchí bù zhǎng = 1(jí wú) de qiēpiàn" -#: extmod/ulab/code/compare/compare.c extmod/ulab/code/ndarray.c -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "operands could not be broadcast together" msgstr "cāozuò shǔ bùnéng yīqǐ guǎngbò" @@ -3594,7 +3676,7 @@ msgstr "cāozuò shǔ bùnéng yīqǐ guǎngbò" msgid "operation is implemented for 1D Boolean arrays only" msgstr "jǐn duì 1D bù ěr shù zǔ shí xiàn cāo zuò" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "operation is not implemented on ndarrays" msgstr "cāozuò wèi zài ndarrays shàng shíxiàn" @@ -3611,11 +3693,19 @@ msgstr "ord yùqí zìfú" msgid "ord() expected a character, but string of length %d found" msgstr "ord() yùqí zìfú, dàn chángdù zìfú chuàn %d" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "chū zhèn liè tài xiǎo" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "chū bì xū shì yí gè fú dòng mì jí zhèn liè" + #: shared-bindings/displayio/Bitmap.c msgid "out of range of source" msgstr "yuán fàn wéi wài" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "out of range of target" msgstr "mù biāo fàn wéi wài" @@ -3636,10 +3726,6 @@ msgstr "yánsè bìxū shì 32 gè zì jié" msgid "palette_index should be an int" msgstr "yánsè suǒyǐn yīnggāi shì yīgè zhěngshù" -#: py/compile.c -msgid "parameter annotation must be an identifier" -msgstr "cānshù zhùshì bìxū shì biāozhì fú" - #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" msgstr "cānshù bìxū shì xùliè a2 zhì a5 de dēngjì shù" @@ -3648,7 +3734,7 @@ msgstr "cānshù bìxū shì xùliè a2 zhì a5 de dēngjì shù" msgid "parameters must be registers in sequence r0 to r3" msgstr "cānshù bìxū shì xùliè r0 zhì r3 de dēngjì qì" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "pixel coordinates out of bounds" msgstr "xiàngsù zuòbiāo chāochū biānjiè" @@ -3671,11 +3757,16 @@ msgstr "cóng kōng mài chōng tán chū" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/cxd56/common-hal/pulseio/PulseIn.c #: ports/nrf/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/pulseio/PulseIn.c #: ports/stm/common-hal/pulseio/PulseIn.c py/objdict.c py/objlist.c py/objset.c #: shared-bindings/ps2io/Ps2.c msgid "pop from empty %q" msgstr "cóng kōng %q dànchū" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "port must be >= 0" +msgstr "duān kǒu bì xū wéi >= 0" + #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" msgstr "pow() 3 cān shǔ bùnéng wéi 0" @@ -3686,12 +3777,17 @@ msgstr "pow() yǒu 3 cānshù xūyào zhěngshù" #: ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h #: ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +#: ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h #: ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h #: ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +#: ports/esp32s2/boards/artisense_rd00/mpconfigboard.h +#: ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h #: ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h #: ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h #: ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +#: ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h #: ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h #: ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h #: ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -3699,6 +3795,7 @@ msgstr "pow() yǒu 3 cānshù xūyào zhěngshù" #: ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h #: ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +#: ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h msgid "pressing boot button at start up.\n" msgstr "Zài qǐdòng shí àn qǐdòng ànniǔ.\n" @@ -3710,13 +3807,21 @@ msgstr "Zài qǐdòng shí àn qǐdòng ànniǔ.\n" msgid "pressing both buttons at start up.\n" msgstr "zài qǐdòng shí tóngshí àn xià liǎng gè ànniǔ.\n" +#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h +msgid "pressing the left button at start up\n" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "lā kǒu zhào yǔ fāng xiàng miàn mó chōng tū" + #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "pull_threshold must be between 1 and 32" -msgstr "" +msgstr "lā lì yù zhí bì xū jiè yú 1 hé 32 zhī jiān" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "push_threshold must be between 1 and 32" -msgstr "" +msgstr "tuī sòng yù zhí bì xū jiè yú 1 hé 32 zhī jiān" #: extmod/modutimeq.c msgid "queue overflow" @@ -3726,7 +3831,7 @@ msgstr "duìliè yìchū" msgid "raw f-strings are not implemented" msgstr "wèi zhíxíng yuánshǐ f-strings" -#: extmod/ulab/code/fft/fft.c +#: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" msgstr "shí bù hé xū bù bìxū děng zhǎng" @@ -3761,7 +3866,7 @@ msgstr "rgb_pins[%d] fùzhì lìng yīgè yǐn jiǎo fēnpèi" msgid "rgb_pins[%d] is not on the same port as clock" msgstr "rgb_pins[%d] yǔ shízhōng bùzài tóng yīgè duānkǒu shàng" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "roll argument must be an ndarray" msgstr "gǔn dòng cān shù bì xū shì ndarray" @@ -3778,6 +3883,7 @@ msgstr "" "huò 'B' de shùzǔ" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" msgstr "qǔyàng lǜ chāochū fànwéi" @@ -3809,7 +3915,7 @@ msgstr "zhěngshù géshì shuōmíng fú 'c' bù yǔnxǔ shǐyòng fúhào" msgid "single '}' encountered in format string" msgstr "zài géshì zìfú chuàn zhōng yù dào de dāngè '}'" -#: extmod/ulab/code/linalg/linalg.c +#: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" msgstr "dàxiǎo jǐn wèi ndarrays dìngyì" @@ -3833,23 +3939,23 @@ msgstr "xiǎo zhěngshù yìchū" msgid "soft reboot\n" msgstr "ruǎn chóngqǐ\n" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "sort argument must be an ndarray" msgstr "páixù cānshù bìxū shì ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" msgstr "sos shùzǔ de xíngzhuàng bìxū wèi (n_section, 6)" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" msgstr "sos [:, 3] yīnggāi quán shì" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" msgstr "sosfilt xūyào diédài cānshù" -#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c msgid "source palette too large" msgstr "yuán miànbǎn tài dà" @@ -3959,7 +4065,7 @@ msgstr "tobytes zhǐ néng duì mì jí shù zǔ diào yòng" msgid "too many arguments provided with the given format" msgstr "tígōng jǐ dìng géshì de cānshù tài duō" -#: extmod/ulab/code/ulab_create.c +#: extmod/ulab/code/ndarray.c extmod/ulab/code/ulab_create.c msgid "too many dimensions" msgstr "chǐ cùn tài duō" @@ -3972,18 +4078,14 @@ msgstr "suǒyǐn tài duō" msgid "too many values to unpack (expected %d)" msgstr "dǎkāi tài duō zhí (yùqí %d)" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays" msgstr "wéi 1D shù zǔ dìng yì xiàn jǐng" -#: extmod/ulab/code/approx/approx.c +#: extmod/ulab/code/numpy/approx/approx.c msgid "trapz is defined for 1D arrays of equal length" msgstr "Trapz shì wèi děng zhǎng de 1D shùzǔ dìngyì de" -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "trigger level must be 0 or 1" -msgstr "chù fā jí bié bì xū wéi 0 huò 1" - #: py/obj.c msgid "tuple/list has wrong length" msgstr "yuán zǔ/lièbiǎo chángdù cuòwù" @@ -4065,7 +4167,7 @@ msgstr "lèixíng '%q' de duìxiàng de wèizhī géshì dàimǎ '%c'" msgid "unknown type" msgstr "wèizhī lèixíng" -#: py/emitnative.c +#: py/compile.c msgid "unknown type '%q'" msgstr "wèizhī lèixíng '%q'" @@ -4118,14 +4220,6 @@ msgstr "Zhí bìxū fúhé %d zì jié" msgid "value_count must be > 0" msgstr "zhí jìshù bìxū wèi > 0" -#: extmod/ulab/code/linalg/linalg.c -msgid "vectors must have same lengths" -msgstr "xiàngliàng bìxū jùyǒu xiāngtóng de chángdù" - -#: ports/esp32s2/common-hal/alarm/pin/__init__.c -msgid "wakeup conflict" -msgstr "huàn xǐng chōng tū" - #: ports/esp32s2/common-hal/watchdog/WatchDogTimer.c msgid "watchdog not initialized" msgstr "wèi chū shǐ huà jiān shì qì" @@ -4134,6 +4228,11 @@ msgstr "wèi chū shǐ huà jiān shì qì" msgid "watchdog timeout must be greater than 0" msgstr "kān mén gǒu chāoshí bìxū dàyú 0" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "width must be from 2 to 8 (inclusive), not %d" +msgstr "kuān dù bì xū cóng 2 dào 8 ( hán ), ér bù shì %d" + #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "width must be greater than zero" msgstr "kuāndù bìxū dàyú líng" @@ -4146,7 +4245,7 @@ msgstr "wèi qǐ yòng WIFI" msgid "window must be <= interval" msgstr "Chuāngkǒu bìxū shì <= jiàngé" -#: extmod/ulab/code/numerical/numerical.c +#: extmod/ulab/code/numpy/numerical/numerical.c msgid "wrong axis index" msgstr "cuò wù de zhóu suǒ yǐn" @@ -4154,7 +4253,8 @@ msgstr "cuò wù de zhóu suǒ yǐn" msgid "wrong axis specified" msgstr "zhǐ dìng de zhóu cuò wù" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/compare/compare.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong input type" msgstr "shūrù lèixíng cuòwù" @@ -4170,7 +4270,7 @@ msgstr "wúfǎ jiě bāo de zhí shù" msgid "wrong operand type" msgstr "cuòwù de cāozuò shù lèixíng" -#: extmod/ulab/code/vector/vectorise.c +#: extmod/ulab/code/numpy/vector/vector.c msgid "wrong output type" msgstr "cuòwù de shūchū lèixíng" @@ -4194,18 +4294,143 @@ msgstr "y zhí chāochū biānjiè" msgid "zero step" msgstr "líng bù" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be an ndarray" msgstr "zi bìxū shì ndarray" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of float type" msgstr "zi bìxū wèi fú diǎn xíng" -#: extmod/ulab/code/filter/filter.c +#: extmod/ulab/code/scipy/signal/signal.c msgid "zi must be of shape (n_section, 2)" msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" +#~ msgid "Viper functions don't currently support more than 4 arguments" +#~ msgstr "Viper hánshù mùqián bù zhīchí chāoguò 4 gè cānshù" + +#~ msgid "address %08x is not aligned to %d bytes" +#~ msgstr "wèi zhǐ %08x wèi yǔ %d wèi yuán zǔ duìqí" + +#~ msgid "function does not take keyword arguments" +#~ msgstr "hánshù méiyǒu guānjiàn cí cānshù" + +#~ msgid "parameter annotation must be an identifier" +#~ msgstr "cānshù zhùshì bìxū shì biāozhì fú" + +#~ msgid "Total data to write is larger than outgoing_packet_length" +#~ msgstr "Yào xiě rù de zǒng shùjù dàyú outgoing_packet_length" + +#~ msgid "IOs 0, 2 & 4 do not support internal pullup in sleep" +#~ msgstr "IOS 0, 2 + 4 bù zhī chí shuì mián zhōng de nèi bù shàng lā" + +#~ msgid "buffer must be a bytes-like object" +#~ msgstr "huǎnchōng qū bìxū shì zì jié lèi duìxiàng" + +#~ msgid "io must be rtc io" +#~ msgstr "IO bì xū shì RTC IO" + +#~ msgid "trigger level must be 0 or 1" +#~ msgstr "chù fā jí bié bì xū wéi 0 huò 1" + +#~ msgid "wakeup conflict" +#~ msgstr "huàn xǐng chōng tū" + +#~ msgid "Attempted heap allocation when MicroPython VM not running." +#~ msgstr "MicroPython VM zài wèi yùnxíng shí chángshì fēnpèi duī." + +#~ msgid "MicroPython NLR jump failed. Likely memory corruption." +#~ msgstr "MicroPython NLR tiào zhuǎn shībài. Kěnéng shì nèicún sǔnhuài." + +#~ msgid "MicroPython fatal error." +#~ msgstr "MicroPython zhìmìng cuòwù." + +#~ msgid "argument must be ndarray" +#~ msgstr "Cānshù bìxū shì ndarray" + +#~ msgid "matrix dimensions do not match" +#~ msgstr "jǔzhèn chǐcùn bù pǐpèi" + +#~ msgid "norm is defined for 1D and 2D arrays" +#~ msgstr "wéi 1D hé 2D shù zǔ dìng yì guī fàn" + +#~ msgid "vectors must have same lengths" +#~ msgstr "xiàngliàng bìxū jùyǒu xiāngtóng de chángdù" + +#~ msgid "Nordic Soft Device failure assertion." +#~ msgstr "Nordic ruǎn shèbèi gùzhàng shēngmíng." + +#~ msgid "Unknown soft device error: %04x" +#~ msgstr "Wèizhī de ruǎn shèbèi cuòwù: %04x" + +#~ msgid "first argument must be an iterable" +#~ msgstr "dì yī gè cānshù bìxū shì kě diédài de" + +#~ msgid "iterables are not of the same length" +#~ msgstr "kě diédài xiàng de chángdù bùtóng" + +#~ msgid "Selected CTS pin not valid" +#~ msgstr "Suǒ xuǎn de CTS yǐn jiǎo wúxiào" + +#~ msgid "Selected RTS pin not valid" +#~ msgstr "Suǒ xuǎn de RTS yǐn jiǎo wúxiào" + +#~ msgid "Could not initialize channel" +#~ msgstr "Wúfǎ chūshǐhuà píndào" + +#~ msgid "Could not initialize timer" +#~ msgstr "Wúfǎ chūshǐhuà jìshí qì" + +#~ msgid "Invalid frequency supplied" +#~ msgstr "Tígōng de pínlǜ wúxiào" + +#~ msgid "Invalid pins for PWMOut" +#~ msgstr "PWMOut de yǐn jiǎo wú xiào" + +#~ msgid "No more channels available" +#~ msgstr "Méiyǒu gèng duō kěyòng píndào" + +#~ msgid "No more timers available" +#~ msgstr "Méiyǒu gèng duō kěyòng de jìshí qì" + +#~ msgid "No more timers available on this pin." +#~ msgstr "Gāi yǐn jiǎo shàng méiyǒu kěyòng de dìngshí qì." + +#~ msgid "" +#~ "Timer was reserved for internal use - declare PWM pins earlier in the " +#~ "program" +#~ msgstr "" +#~ "Dìngshí qì bǎoliú gōng nèibù shǐyòng-zài chéngxù de qiánmiàn shēngmíng " +#~ "PWM yǐn jiǎo" + +#~ msgid "Group full" +#~ msgstr "Fēnzǔ yǐ mǎn" + +#~ msgid "In buffer elements must be 4 bytes long or less" +#~ msgstr "" +#~ "zài huǎn chōng yuán jiàn zhōng bì xū shì 4 zì jié cháng huò gèng shǎo" + +#~ msgid "Out buffer elements must be 4 bytes long or less" +#~ msgstr "chū huǎn chōng yuán jiàn bì xū shì 4 zì jié cháng huò gèng shǎo" + +#~ msgid "UART not yet supported" +#~ msgstr "UART shàng wèi shòu zhī chí" + +#~ msgid "bits must be 7, 8 or 9" +#~ msgstr "bǐtè bìxū shì 7,8 huò 9" + +#~ msgid "Only IN/OUT of up to 8 supported" +#~ msgstr "jǐn zhī chí zuì duō 8 gè IN/OUT" + +#~ msgid "SDA or SCL needs a pull up" +#~ msgstr "SDA huò SCL xūyào lādòng" + +#~ msgid "Invalid use of TLS Socket" +#~ msgstr "TLS tào jiē zì de wú xiào shǐ yòng" + +#~ msgid "Issue setting SO_REUSEADDR" +#~ msgstr "wèn tí shè zhì SO_REUSEADDR" + #~ msgid "%d address pins and %d rgb pins indicate a height of %d, not %d" #~ msgstr "" #~ "%d dìzhǐ yǐn jiǎo hé %d rgb yǐn jiǎo jiāng gāodù biǎoshì wèi %d, ér bùshì " @@ -4369,9 +4594,6 @@ msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" #~ msgid "can't convert to float" #~ msgstr "bùnéng zhuǎnhuàn wèi fú diǎn" -#~ msgid "can't convert to int" -#~ msgstr "bùnéng zhuǎnhuàn wèi int" - #~ msgid "object '%s' is not a tuple or list" #~ msgstr "duìxiàng '%s' bùshì yuán zǔ huò lièbiǎo" diff --git a/main.c b/main.c index d9cdcca1da59e..c30c2f960db05 100755 --- a/main.c +++ b/main.c @@ -60,6 +60,7 @@ #include "supervisor/shared/translate.h" #include "supervisor/shared/workflow.h" #include "supervisor/usb.h" +#include "supervisor/workflow.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Processor.h" @@ -69,6 +70,19 @@ #include "shared-bindings/alarm/__init__.h" #endif +#if CIRCUITPY_BLEIO +#include "shared-bindings/_bleio/__init__.h" +#include "supervisor/shared/bluetooth.h" +#endif + +#if CIRCUITPY_BOARD +#include "shared-module/board/__init__.h" +#endif + +#if CIRCUITPY_CANIO +#include "common-hal/canio/CAN.h" +#endif + #if CIRCUITPY_DISPLAYIO #include "shared-module/displayio/__init__.h" #endif @@ -81,17 +95,8 @@ #include "shared-module/network/__init__.h" #endif -#if CIRCUITPY_BOARD -#include "shared-module/board/__init__.h" -#endif - -#if CIRCUITPY_BLEIO -#include "shared-bindings/_bleio/__init__.h" -#include "supervisor/shared/bluetooth.h" -#endif - -#if CIRCUITPY_CANIO -#include "common-hal/canio/CAN.h" +#if CIRCUITPY_USB_CDC +#include "shared-module/usb_cdc/__init__.h" #endif #if CIRCUITPY_WIFI @@ -157,7 +162,7 @@ STATIC void start_mp(supervisor_allocation* heap) { #if CIRCUITPY_ALARM // Record which alarm woke us up, if any. An object may be created so the heap must be functional. - alarm_save_wake_alarm(); + shared_alarm_save_wake_alarm(); // Reset alarm module only after we retrieved the wakeup alarm. alarm_reset(); #endif @@ -185,6 +190,10 @@ STATIC void stop_mp(void) { background_callback_reset(); + #if CIRCUITPY_USB + usb_background(); + #endif + gc_deinit(); } @@ -300,8 +309,6 @@ STATIC bool run_code_py(safe_mode_t safe_mode) { } #endif - // TODO: on deep sleep, make sure display is refreshed before sleeping (for e-ink). - cleanup_after_vm(heap); if (result.return_code & PYEXEC_FORCED_EXIT) { @@ -324,12 +331,12 @@ STATIC bool run_code_py(safe_mode_t safe_mode) { rgb_status_animation_t animation; prep_rgb_status_animation(&result, found_main, safe_mode, &animation); - bool asleep = false; + bool fake_sleeping = false; while (true) { RUN_BACKGROUND_TASKS; if (reload_requested) { #if CIRCUITPY_ALARM - if (asleep) { + if (fake_sleeping) { board_init(); } #endif @@ -340,7 +347,7 @@ STATIC bool run_code_py(safe_mode_t safe_mode) { if (serial_connected() && serial_bytes_available()) { #if CIRCUITPY_ALARM - if (asleep) { + if (fake_sleeping) { board_init(); } #endif @@ -356,7 +363,7 @@ STATIC bool run_code_py(safe_mode_t safe_mode) { // an alarm alerts faster than our USB delay or if we pretended to deep // sleep. #if CIRCUITPY_ALARM - if (asleep && alarm_woken_from_sleep()) { + if (fake_sleeping && common_hal_alarm_woken_from_sleep()) { serial_write_compressed(translate("Woken up by alarm.\n")); board_init(); supervisor_set_run_reason(RUN_REASON_STARTUP); @@ -395,20 +402,15 @@ STATIC bool run_code_py(safe_mode_t safe_mode) { if (result.return_code & PYEXEC_DEEP_SLEEP) { // Make sure we have been awake long enough for USB to connect (enumeration delay). int64_t connecting_delay_ticks = CIRCUITPY_USB_CONNECTED_SLEEP_DELAY * 1024 - port_get_raw_ticks(NULL); - if (connecting_delay_ticks > 0) { - // Set when we've waited long enough so that we wake up from the - // port_idle_until_interrupt below and loop around to the real deep - // sleep in the else clause. - port_interrupt_after_ticks(connecting_delay_ticks); - // Deep sleep if we're not connected to a host. - } else if (!asleep) { - asleep = true; + // Until it's safe to decide whether we're real/fake sleeping, just run the RGB + if (connecting_delay_ticks < 0 && !fake_sleeping) { + fake_sleeping = true; new_status_color(BLACK); board_deinit(); if (!supervisor_workflow_active()) { // Enter true deep sleep. When we wake up we'll be back at the // top of main(), not in this loop. - alarm_enter_deep_sleep(); + common_hal_alarm_enter_deep_sleep(); // Does not return. } else { serial_write_compressed(translate("Pretending to deep sleep until alarm, CTRL-C or file write.\n")); @@ -417,7 +419,7 @@ STATIC bool run_code_py(safe_mode_t safe_mode) { } #endif - if (!asleep) { + if (!fake_sleeping) { tick_rgb_status_animation(&animation); } else { // This waits until a pretend deep sleep alarm occurs. They are set @@ -425,7 +427,11 @@ STATIC bool run_code_py(safe_mode_t safe_mode) { // it may also return due to another interrupt, that's why we check // for deep sleep alarms above. If it wasn't a deep sleep alarm, // then we'll idle here again. - port_idle_until_interrupt(); + #if CIRCUITPY_ALARM + common_hal_alarm_pretending_deep_sleep(); + #else + port_idle_until_interrupt(); + #endif } } } diff --git a/mpy-cross/Makefile b/mpy-cross/Makefile index 3ff379ed36f74..200080bbe53ad 100644 --- a/mpy-cross/Makefile +++ b/mpy-cross/Makefile @@ -9,6 +9,8 @@ ifneq ($(findstring undefine,$(.FEATURES)),) override undefine COPT override undefine CFLAGS_EXTRA override undefine LDFLAGS_EXTRA +override undefine MICROPY_FORCE_32BIT +override undefine CROSS_COMPILE override undefine FROZEN_DIR override undefine FROZEN_MPY_DIR override undefine BUILD diff --git a/mpy-cross/fmode.c b/mpy-cross/fmode.c index b1fa3fc857185..f32a4af5d335b 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 2216fad311daf..9a975af8dbff8 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 7a1012b8fc795..6e99ea2408206 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 464c9113d5a34..74bb774afcd68 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/mpy-cross/mphalport.h b/mpy-cross/mphalport.h index 245b99c4c3f42..b45ff339bad8e 100644 --- a/mpy-cross/mphalport.h +++ b/mpy-cross/mphalport.h @@ -2,4 +2,5 @@ // // SPDX-License-Identifier: MIT -// empty file +// prevent including extmod/virtpin.h +#define mp_hal_pin_obj_t diff --git a/mpy-cross/mpy-cross.mk b/mpy-cross/mpy-cross.mk index 629054af9e485..c6ef9d8165963 100644 --- a/mpy-cross/mpy-cross.mk +++ b/mpy-cross/mpy-cross.mk @@ -22,8 +22,8 @@ UNAME_S := $(shell uname -s) # include py core make definitions include $(TOP)/py/py.mk -INC += -I. -INC += -I$(TOP) +INC += -I. +INC += -I$(TOP) INC += -I$(BUILD) # compiler settings @@ -79,7 +79,7 @@ ifneq (,$(findstring mingw,$(COMPILER_TARGET))) SRC_C += fmode.c endif -OBJ = $(PY_O) +OBJ = $(PY_CORE_O) OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) $(BUILD)/supervisor/shared/translate.o: $(HEADER_BUILD)/qstrdefs.generated.h diff --git a/ports/atmel-samd/Makefile b/ports/atmel-samd/Makefile index 58c1c0d60ebd6..48724af0c875d 100644 --- a/ports/atmel-samd/Makefile +++ b/ports/atmel-samd/Makefile @@ -122,7 +122,7 @@ CFLAGS += -ftree-vrp $(echo PERIPHERALS_CHIP_FAMILY=$(PERIPHERALS_CHIP_FAMILY)) #Debugging/Optimization ifeq ($(DEBUG), 1) - CFLAGS += -ggdb3 -Og + CFLAGS += -ggdb3 -Og -Os # You may want to disable -flto if it interferes with debugging. CFLAGS += -flto -flto-partition=none # You may want to enable these flags to make setting breakpoints easier. 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 b97131f0bc286..a3d67d8b3bd7c 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 85d05fc5043ec..007a72d068ae1 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 74ec2bee953d2..193298ed913b6 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 90e9b07357475..d651ca33a830c 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 df6dac3f78872..b0f570b5e5f6e 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 6f4f01a7e6786..1dda85a693cbc 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 cd11866059bc3..f7f79fada1ed5 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 cd411154c7645..b438619773efb 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 38d48e9b67c51..3bc688295bdf4 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 be1fa3c9e07da..b2629e1239792 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 6f4f01a7e6786..1dda85a693cbc 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 cd11866059bc3..f7f79fada1ed5 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 cd411154c7645..b438619773efb 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 38d48e9b67c51..3bc688295bdf4 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 be1fa3c9e07da..b2629e1239792 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 6f4f01a7e6786..1dda85a693cbc 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 cd11866059bc3..f7f79fada1ed5 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 cd411154c7645..b438619773efb 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 38d48e9b67c51..3bc688295bdf4 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 be1fa3c9e07da..b2629e1239792 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 c6c636160d537..7b1ca42c06709 100644 --- a/ports/atmel-samd/audio_dma.c +++ b/ports/atmel-samd/audio_dma.c @@ -38,14 +38,22 @@ #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]; static bool audio_dma_allocated[AUDIO_DMA_CHANNEL_COUNT]; -uint8_t audio_dma_allocate_channel(void) { +uint8_t find_sync_event_channel_raise() { + uint8_t event_channel = find_sync_event_channel(); + if (event_channel >= EVSYS_SYNCH_NUM) { + mp_raise_RuntimeError(translate("All sync event channels in use")); + } + return event_channel; +} + +uint8_t dma_allocate_channel(void) { uint8_t channel; for (channel = 0; channel < AUDIO_DMA_CHANNEL_COUNT; channel++) { if (!audio_dma_allocated[channel]) { @@ -56,7 +64,7 @@ uint8_t audio_dma_allocate_channel(void) { return channel; // i.e., return failure } -void audio_dma_free_channel(uint8_t channel) { +void dma_free_channel(uint8_t channel) { assert(channel < AUDIO_DMA_CHANNEL_COUNT); assert(audio_dma_allocated[channel]); audio_dma_disable_channel(channel); @@ -64,20 +72,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 +102,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 +127,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 +145,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 +163,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,23 +172,23 @@ 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) { - uint8_t dma_channel = audio_dma_allocate_channel(); +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 = dma_allocate_channel(); if (dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { return AUDIO_DMA_DMA_BUSY; } @@ -199,18 +209,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,18 +231,14 @@ 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; } // We're likely double buffering so set up the block interrupts. turn_on_event_system(); - dma->event_channel = find_sync_event_channel(); - - if (dma->event_channel >= EVSYS_SYNCH_NUM) { - mp_raise_RuntimeError(translate("All sync event channels in use")); - } + dma->event_channel = find_sync_event_channel_raise(); init_event_channel_interrupt(dma->event_channel, CORE_GCLK, EVSYS_ID_GEN_DMAC_CH_0 + dma_channel); // We keep the audio_dma_t for internal use and the sample as a root pointer because it @@ -257,26 +263,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,27 +299,27 @@ 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); disable_event_channel(dma->event_channel); MP_STATE_PORT(playing_audio)[channel] = NULL; audio_dma_state[channel] = NULL; - audio_dma_free_channel(dma->dma_channel); + dma_free_channel(dma->dma_channel); } 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 +328,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 +343,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 +358,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 +368,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 +376,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 4fffd06b8f105..4e7d193b1dbdc 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,11 +63,11 @@ 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); -void audio_dma_free_channel(uint8_t channel); +uint8_t dma_allocate_channel(void); +void dma_free_channel(uint8_t channel); // This sets everything up but doesn't start the timer. // Sample is the python object for the sample to play. @@ -78,23 +78,25 @@ 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); +uint8_t find_sync_event_channel_raise(void); + #endif // MICROPY_INCLUDED_ATMEL_SAMD_AUDIO_DMA_H diff --git a/ports/atmel-samd/background.c b/ports/atmel-samd/background.c index 62c233a3f8385..237395b6b9605 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 478a10fcd4a62..9375a7a8489f0 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 ccc8f10d1019b..a4c11556b34ed 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 6e9b68ccc63fe..207a6d52e63ef 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 9e3be4e6a0834..0b5d3a267d68f 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/8086_commander/mpconfigboard.mk b/ports/atmel-samd/boards/8086_commander/mpconfigboard.mk index f976dfe787cb8..c7918ad05c99b 100644 --- a/ports/atmel-samd/boards/8086_commander/mpconfigboard.mk +++ b/ports/atmel-samd/boards/8086_commander/mpconfigboard.mk @@ -7,16 +7,14 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q128JV_SQ" +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 CIRCUITPY_USB_MIDI = 0 SUPEROPT_GC = 0 - -CFLAGS_INLINE_LIMIT = 60 +SUPEROPT_VM = 0 CIRCUITPY_GAMEPAD = 1 CIRCUITPY_BUSDEVICE = 1 diff --git a/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/board.c new file mode 100644 index 0000000000000..cde441b3d9fab --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/board.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.h new file mode 100644 index 0000000000000..3cd85ac1bce76 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.h @@ -0,0 +1,58 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit NeoKey Trinkey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_NEOPIXEL (&pin_PA15) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define IGNORE_PIN_PA00 1 +#define IGNORE_PIN_PA01 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_PA08 1 +#define IGNORE_PIN_PA09 1 +#define IGNORE_PIN_PA10 1 +#define IGNORE_PIN_PA11 1 +#define IGNORE_PIN_PA12 1 +#define IGNORE_PIN_PA13 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA16 1 +#define IGNORE_PIN_PA17 1 +#define IGNORE_PIN_PA18 1 +#define IGNORE_PIN_PA19 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +// 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_PA27 1 +#define IGNORE_PIN_PA29 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB00 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 diff --git a/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000000..56cbede39ff6c --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/mpconfigboard.mk @@ -0,0 +1,34 @@ +USB_VID = 0x239A +USB_PID = 0x8100 +USB_PRODUCT = "NeoKey Trinkey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE + +CIRCUITPY_ANALOGIO = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAMD = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_BUSIO = 0 +CIRCUITPY_STORAGE = 1 + +CIRCUITPY_MATH = 1 +CIRCUITPY_PIXELBUF = 1 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 1 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/pins.c new file mode 100644 index 0000000000000..df8dfb0bfa3cb --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_neokey_trinkey_m0/pins.c @@ -0,0 +1,8 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_TOUCH), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_SWITCH), MP_ROM_PTR(&pin_PA28) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/board.c new file mode 100644 index 0000000000000..cde441b3d9fab --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/board.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.h new file mode 100644 index 0000000000000..a760fbe376512 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.h @@ -0,0 +1,58 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit ProxLight Trinkey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_NEOPIXEL (&pin_PA15) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define IGNORE_PIN_PA01 1 +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA06 1 +#define IGNORE_PIN_PA08 1 +#define IGNORE_PIN_PA09 1 +#define IGNORE_PIN_PA10 1 +#define IGNORE_PIN_PA11 1 +#define IGNORE_PIN_PA12 1 +#define IGNORE_PIN_PA13 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA18 1 +#define IGNORE_PIN_PA19 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +// 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_PA27 1 +#define IGNORE_PIN_PA28 1 +#define IGNORE_PIN_PA29 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB00 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 + +#define DEFAULT_I2C_BUS_SCL (&pin_PA17) +#define DEFAULT_I2C_BUS_SDA (&pin_PA16) diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000000..92e7a17f3e144 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk @@ -0,0 +1,33 @@ +USB_VID = 0x239A +USB_PID = 0x8104 +USB_PRODUCT = "ProxLight Trinkey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE + +CIRCUITPY_ANALOGIO = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAMD = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_BUSIO = 1 +CIRCUITPY_STORAGE = 1 + +CIRCUITPY_MATH = 1 +CIRCUITPY_PIXELBUF = 0 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 1 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/pins.c new file mode 100644 index 0000000000000..21410f8ad1e04 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/pins.c @@ -0,0 +1,15 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_INTERRUPT), MP_ROM_PTR(&pin_PA00) }, + + { MP_ROM_QSTR(MP_QSTR_TOUCH2), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH1), MP_ROM_PTR(&pin_PA07) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA17) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/board.c new file mode 100644 index 0000000000000..cde441b3d9fab --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/board.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.h new file mode 100644 index 0000000000000..2b06b31ede397 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.h @@ -0,0 +1,54 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit Rotary Trinkey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_NEOPIXEL (&pin_PA01) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA03 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA08 1 +#define IGNORE_PIN_PA09 1 +#define IGNORE_PIN_PA10 1 +#define IGNORE_PIN_PA11 1 +#define IGNORE_PIN_PA12 1 +#define IGNORE_PIN_PA13 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA15 1 +#define IGNORE_PIN_PA16 1 +#define IGNORE_PIN_PA17 1 +#define IGNORE_PIN_PA18 1 +#define IGNORE_PIN_PA19 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +// 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_PA28 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB00 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 diff --git a/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000000..29cc9ee195ada --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/mpconfigboard.mk @@ -0,0 +1,34 @@ +USB_VID = 0x239A +USB_PID = 0x80FC +USB_PRODUCT = "Rotary Trinkey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE + +CIRCUITPY_ANALOGIO = 0 +CIRCUITPY_ROTARYIO = 1 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAMD = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_BUSIO = 0 +CIRCUITPY_STORAGE = 1 + +CIRCUITPY_MATH = 0 +CIRCUITPY_PIXELBUF = 1 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 0 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/pins.c new file mode 100644 index 0000000000000..cd014fcb645cf --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_rotary_trinkey_m0/pins.c @@ -0,0 +1,9 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_ROTB), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_ROTA), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_SWITCH), MP_ROM_PTR(&pin_PA27) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/board.c b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/board.c new file mode 100644 index 0000000000000..cde441b3d9fab --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/board.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.h new file mode 100644 index 0000000000000..1d9a4122df92d --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.h @@ -0,0 +1,58 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit Slide Trinkey M0" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_NEOPIXEL (&pin_PA06) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define IGNORE_PIN_PA00 1 +#define IGNORE_PIN_PA01 1 +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA03 1 +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA08 1 +#define IGNORE_PIN_PA09 1 +#define IGNORE_PIN_PA10 1 +#define IGNORE_PIN_PA11 1 +#define IGNORE_PIN_PA12 1 +#define IGNORE_PIN_PA13 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA15 1 +#define IGNORE_PIN_PA16 1 +#define IGNORE_PIN_PA17 1 +#define IGNORE_PIN_PA18 1 +#define IGNORE_PIN_PA19 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +// 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_PA27 1 +#define IGNORE_PIN_PA29 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB00 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.mk new file mode 100644 index 0000000000000..2bc2def52ea22 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/mpconfigboard.mk @@ -0,0 +1,35 @@ +USB_VID = 0x239A +USB_PID = 0x8102 +USB_PRODUCT = "Slide Trinkey M0" +USB_MANUFACTURER = "Adafruit Industries LLC" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE + +CIRCUITPY_ANALOGIO = 1 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAMD = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_BUSIO = 0 +CIRCUITPY_STORAGE = 1 + +CIRCUITPY_MATH = 1 +CIRCUITPY_PIXELBUF = 1 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 1 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SimpleMath +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/pins.c b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/pins.c new file mode 100644 index 0000000000000..c48c69206a854 --- /dev/null +++ b/ports/atmel-samd/boards/adafruit_slide_trinkey_m0/pins.c @@ -0,0 +1,8 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + //{ MP_ROM_QSTR(MP_QSTR_TOUCH), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_POTENTIOMETER), MP_ROM_PTR(&pin_PA07) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c b/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c index 5973eeec1b4b3..c67701512fb13 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 cafc82605d1e6..3882c2b6dbacd 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/aloriumtech_evo_m51/mpconfigboard.mk b/ports/atmel-samd/boards/aloriumtech_evo_m51/mpconfigboard.mk index 34301da3f00c8..3b5b05020dd08 100644 --- a/ports/atmel-samd/boards/aloriumtech_evo_m51/mpconfigboard.mk +++ b/ports/atmel-samd/boards/aloriumtech_evo_m51/mpconfigboard.mk @@ -9,7 +9,6 @@ CHIP_VARIANT = SAMD51P19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/arduino_mkr1300/board.c b/ports/atmel-samd/boards/arduino_mkr1300/board.c index 112b173eccb51..7af05ba45a53e 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_mkr1300/mpconfigboard.mk b/ports/atmel-samd/boards/arduino_mkr1300/mpconfigboard.mk index 36d463697d3f8..1fd96b0aeeab0 100644 --- a/ports/atmel-samd/boards/arduino_mkr1300/mpconfigboard.mk +++ b/ports/atmel-samd/boards/arduino_mkr1300/mpconfigboard.mk @@ -9,5 +9,6 @@ CHIP_FAMILY = samd21 INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 + SUPEROPT_GC = 0 SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/arduino_mkrzero/mpconfigboard.mk b/ports/atmel-samd/boards/arduino_mkrzero/mpconfigboard.mk index 20307fc051c07..fabe52ce2349f 100644 --- a/ports/atmel-samd/boards/arduino_mkrzero/mpconfigboard.mk +++ b/ports/atmel-samd/boards/arduino_mkrzero/mpconfigboard.mk @@ -12,4 +12,3 @@ CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 SUPEROPT_VM = 0 -CFLAGS_INLINE_LIMIT = 40 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 112b173eccb51..7af05ba45a53e 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_nano_33_iot/mpconfigboard.mk b/ports/atmel-samd/boards/arduino_nano_33_iot/mpconfigboard.mk index 07b1b98002e49..c16c53e6d644c 100644 --- a/ports/atmel-samd/boards/arduino_nano_33_iot/mpconfigboard.mk +++ b/ports/atmel-samd/boards/arduino_nano_33_iot/mpconfigboard.mk @@ -11,5 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/arduino_zero/board.c b/ports/atmel-samd/boards/arduino_zero/board.c index 112b173eccb51..7af05ba45a53e 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/arduino_zero/mpconfigboard.mk b/ports/atmel-samd/boards/arduino_zero/mpconfigboard.mk index a5722c9ade233..697ec02c368b7 100644 --- a/ports/atmel-samd/boards/arduino_zero/mpconfigboard.mk +++ b/ports/atmel-samd/boards/arduino_zero/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 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 6baa43ffaa3cb..84960e73cf2cd 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/bast_pro_mini_m0/mpconfigboard.mk b/ports/atmel-samd/boards/bast_pro_mini_m0/mpconfigboard.mk index 6a2c896197d60..ec037837e5d2e 100644 --- a/ports/atmel-samd/boards/bast_pro_mini_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/bast_pro_mini_m0/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/bdmicro_vina_d21/board.c b/ports/atmel-samd/boards/bdmicro_vina_d21/board.c index bb1c5335c18af..bb6ad8bc0dbc0 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_d21/mpconfigboard.mk b/ports/atmel-samd/boards/bdmicro_vina_d21/mpconfigboard.mk index cff5a32d1c8a2..fea765c3f05bc 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d21/mpconfigboard.mk +++ b/ports/atmel-samd/boards/bdmicro_vina_d21/mpconfigboard.mk @@ -7,11 +7,11 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "MX25L51245G","GD25S512MD" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_MSGPACK = 0 diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/board.c b/ports/atmel-samd/boards/bdmicro_vina_d51/board.c index bb1c5335c18af..7af05ba45a53e 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/board.c +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/board.c @@ -26,18 +26,9 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "hal/include/hal_gpio.h" -void board_init(void) -{ - // struct port_config pin_conf; - // port_get_config_defaults(&pin_conf); - // - // pin_conf.direction = PORT_PIN_DIR_OUTPUT; - // port_pin_set_config(MICROPY_HW_LED_TX, &pin_conf); - // port_pin_set_output_level(MICROPY_HW_LED_TX, true); - // - // port_pin_set_config(MICROPY_HW_LED_RX, &pin_conf); - // port_pin_set_output_level(MICROPY_HW_LED_RX, true); +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h index 8b015df05ed2b..24d78b8ed100e 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.h @@ -1,3 +1,6 @@ +// More than one revision of this board is available. +// This board specifies PCB Revision 10 + #define MICROPY_HW_BOARD_NAME "BDMICRO VINA-D51" #define MICROPY_HW_MCU_NAME "samd51n20" @@ -12,13 +15,13 @@ #define BOARD_HAS_CRYSTAL 1 -#define DEFAULT_I2C_BUS_SCL (&pin_PA16) -#define DEFAULT_I2C_BUS_SDA (&pin_PA17) -#define DEFAULT_UART_BUS_RX (&pin_PB20) +#define DEFAULT_I2C_BUS_SCL (&pin_PA12) +#define DEFAULT_I2C_BUS_SDA (&pin_PA13) #define DEFAULT_UART_BUS_TX (&pin_PB21) +#define DEFAULT_UART_BUS_RX (&pin_PB20) +#define DEFAULT_SPI_BUS_SCK (&pin_PC28) #define DEFAULT_SPI_BUS_MISO (&pin_PB23) #define DEFAULT_SPI_BUS_MOSI (&pin_PC27) -#define DEFAULT_SPI_BUS_SCK (&pin_PC28) #define MICROPY_HW_LED_STATUS (&pin_PA23) #define MICROPY_HW_LED_RX (&pin_PC05) #define MICROPY_HW_LED_TX (&pin_PC06) diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk index f1b2f4c1d99de..13487413f4fcb 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/mpconfigboard.mk @@ -1,5 +1,8 @@ +# More than one revision of this board is available. +# This board specifies PCB Revision 10 + USB_VID = 0x31e2 -USB_PID = 0x2011 +USB_PID = 0x2021 USB_PRODUCT = "VINA-D51" USB_MANUFACTURER = "BDMICRO LLC" @@ -7,6 +10,5 @@ CHIP_VARIANT = SAMD51N20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "MX25L51245G","GD25S512MD" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c b/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c index 8eeab8a9a5bf9..e7595d9789d28 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/pins.c @@ -1,3 +1,6 @@ +// More than one revision of this board is available. +// This board specifies PCB Revision 10 + #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_global_dict_table[] = { @@ -13,6 +16,42 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PB04) }, { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PB05) }, { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_AUX_1), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_TX), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_MOSI), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_I2C_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_MOSI), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_TX), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_AUX_10), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_IRQ), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_AUX_11), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_GPIO_3), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_AUX_12), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_GPIO_1), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_AUX_3), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_RTS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_SS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_SS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO0), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_AUX_4), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_RESET), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RESET), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_AUX_5), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_CTS), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_MISO), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_MISO), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO2), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_AUX_6), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_EN), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_CH_PD), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_AUX_8), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_UART_RX), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_SPI_SCK), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_I2C_SCL), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_SCK), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RX), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_AUX_9), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_ATW01_WAKE), MP_ROM_PTR(&pin_PA27) }, { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PB31) }, { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PC16) }, { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PC13) }, @@ -30,26 +69,10 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PC12) }, { MP_ROM_QSTR(MP_QSTR_DAC0), MP_ROM_PTR(&pin_PA02) }, { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_EN), MP_ROM_PTR(&pin_PC15) }, - { MP_ROM_QSTR(MP_QSTR_E5), MP_ROM_PTR(&pin_PC15) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO0), MP_ROM_PTR(&pin_PA18) }, - { MP_ROM_QSTR(MP_QSTR_E3), MP_ROM_PTR(&pin_PA18) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO2), MP_ROM_PTR(&pin_PA19) }, - { MP_ROM_QSTR(MP_QSTR_E4), MP_ROM_PTR(&pin_PA19) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_RESET), MP_ROM_PTR(&pin_PC14) }, - { MP_ROM_QSTR(MP_QSTR_E6), MP_ROM_PTR(&pin_PC14) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_RX), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_UART3_RX), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_I2C3_SCL), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_E2), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_ESP01_TX), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_UART3_TX), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_I2C3_SDA), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_E1), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PA16) }, - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA16) }, - { MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PA17) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA13) }, { MP_ROM_QSTR(MP_QSTR_I2S_FS_0), MP_ROM_PTR(&pin_PA20) }, { MP_ROM_QSTR(MP_QSTR_I2S_MCK_0), MP_ROM_PTR(&pin_PB17) }, { MP_ROM_QSTR(MP_QSTR_I2S_SCK_0), MP_ROM_PTR(&pin_PB16) }, @@ -65,13 +88,13 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_RS485_RX), MP_ROM_PTR(&pin_PB03) }, { MP_ROM_QSTR(MP_QSTR_RS485_TE), MP_ROM_PTR(&pin_PB00) }, { MP_ROM_QSTR(MP_QSTR_RS485_TX), MP_ROM_PTR(&pin_PB02) }, - { MP_ROM_QSTR(MP_QSTR_SPI_MISO), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_MISO), MP_ROM_PTR(&pin_PB23) }, { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PB23) }, - { MP_ROM_QSTR(MP_QSTR_SPI_MOSI), MP_ROM_PTR(&pin_PC27) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_MOSI), MP_ROM_PTR(&pin_PC27) }, { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PC27) }, - { MP_ROM_QSTR(MP_QSTR_SPI_SCK), MP_ROM_PTR(&pin_PC28) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_SCK), MP_ROM_PTR(&pin_PC28) }, { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PC28) }, - { MP_ROM_QSTR(MP_QSTR_SPI_SS), MP_ROM_PTR(&pin_PB22) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_SS), MP_ROM_PTR(&pin_PB22) }, { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_PB22) }, { MP_ROM_QSTR(MP_QSTR_UART1_CTS), MP_ROM_PTR(&pin_PC25) }, { MP_ROM_QSTR(MP_QSTR_UART1_RTS), MP_ROM_PTR(&pin_PC24) }, diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/board.c b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/board.c new file mode 100644 index 0000000000000..bb6ad8bc0dbc0 --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/board.c @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +void board_init(void) { + // struct port_config pin_conf; + // port_get_config_defaults(&pin_conf); + // + // pin_conf.direction = PORT_PIN_DIR_OUTPUT; + // port_pin_set_config(MICROPY_HW_LED_TX, &pin_conf); + // port_pin_set_output_level(MICROPY_HW_LED_TX, true); + // + // port_pin_set_config(MICROPY_HW_LED_RX, &pin_conf); + // port_pin_set_output_level(MICROPY_HW_LED_RX, true); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.h b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.h new file mode 100644 index 0000000000000..8b015df05ed2b --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.h @@ -0,0 +1,28 @@ +#define MICROPY_HW_BOARD_NAME "BDMICRO VINA-D51" +#define MICROPY_HW_MCU_NAME "samd51n20" + +#define CIRCUITPY_MCU_FAMILY samd51 + +// These are pins not to reset. +// Don't reset QSPI data pins +#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11) +#define MICROPY_PORT_C (0) +#define MICROPY_PORT_D (0) + +#define BOARD_HAS_CRYSTAL 1 + +#define DEFAULT_I2C_BUS_SCL (&pin_PA16) +#define DEFAULT_I2C_BUS_SDA (&pin_PA17) +#define DEFAULT_UART_BUS_RX (&pin_PB20) +#define DEFAULT_UART_BUS_TX (&pin_PB21) +#define DEFAULT_SPI_BUS_MISO (&pin_PB23) +#define DEFAULT_SPI_BUS_MOSI (&pin_PC27) +#define DEFAULT_SPI_BUS_SCK (&pin_PC28) +#define MICROPY_HW_LED_STATUS (&pin_PA23) +#define MICROPY_HW_LED_RX (&pin_PC05) +#define MICROPY_HW_LED_TX (&pin_PC06) + +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.mk b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.mk new file mode 100644 index 0000000000000..de350f7ab0e57 --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x31e2 +USB_PID = 0x2011 +USB_PRODUCT = "VINA-D51" +USB_MANUFACTURER = "BDMICRO LLC" + +CHIP_VARIANT = SAMD51N20A +CHIP_FAMILY = samd51 + +QSPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "MX25L51245G","GD25S512MD" +LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/pins.c b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/pins.c new file mode 100644 index 0000000000000..8eeab8a9a5bf9 --- /dev/null +++ b/ports/atmel-samd/boards/bdmicro_vina_d51_pcb7/pins.c @@ -0,0 +1,90 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_PC00) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PC02) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PB31) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PC16) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PC17) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PC18) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PC19) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PC20) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PC21) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PB18) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PB19) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PC12) }, + { MP_ROM_QSTR(MP_QSTR_DAC0), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_EN), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_E5), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO0), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_E3), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_GPIO2), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_E4), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RESET), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_E6), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_RX), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_UART3_RX), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_I2C3_SCL), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_E2), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_ESP01_TX), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_UART3_TX), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_I2C3_SDA), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_E1), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_I2S_FS_0), MP_ROM_PTR(&pin_PA20) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MCK_0), MP_ROM_PTR(&pin_PB17) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SCK_0), MP_ROM_PTR(&pin_PB16) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SDI), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SDO), MP_ROM_PTR(&pin_PA21) }, + { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_LED_STATUS), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_LED_RX), MP_ROM_PTR(&pin_PC05) }, + { MP_ROM_QSTR(MP_QSTR_LED_TX), MP_ROM_PTR(&pin_PC06) }, + { MP_ROM_QSTR(MP_QSTR_RS485_RE), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_RS485_RX), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_RS485_TE), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_RS485_TX), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_SPI_MISO), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_SPI_MOSI), MP_ROM_PTR(&pin_PC27) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PC27) }, + { MP_ROM_QSTR(MP_QSTR_SPI_SCK), MP_ROM_PTR(&pin_PC28) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PC28) }, + { MP_ROM_QSTR(MP_QSTR_SPI_SS), MP_ROM_PTR(&pin_PB22) }, + { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_PB22) }, + { MP_ROM_QSTR(MP_QSTR_UART1_CTS), MP_ROM_PTR(&pin_PC25) }, + { MP_ROM_QSTR(MP_QSTR_UART1_RTS), MP_ROM_PTR(&pin_PC24) }, + { MP_ROM_QSTR(MP_QSTR_UART1_RX), MP_ROM_PTR(&pin_PB24) }, + { MP_ROM_QSTR(MP_QSTR_UART1_TX), MP_ROM_PTR(&pin_PB25) }, + { MP_ROM_QSTR(MP_QSTR_UART2_RX), MP_ROM_PTR(&pin_PB20) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PB20) }, + { MP_ROM_QSTR(MP_QSTR_I2C2_SCL), MP_ROM_PTR(&pin_PB20) }, + { MP_ROM_QSTR(MP_QSTR_UART2_TX), MP_ROM_PTR(&pin_PB21) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PB21) }, + { MP_ROM_QSTR(MP_QSTR_I2C2_SDA), MP_ROM_PTR(&pin_PB21) }, + { 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/blm_badge/pins.c b/ports/atmel-samd/boards/blm_badge/pins.c index 6e7d8da7548b3..805a713893cf7 100644 --- a/ports/atmel-samd/boards/blm_badge/pins.c +++ b/ports/atmel-samd/boards/blm_badge/pins.c @@ -37,6 +37,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_LIGHT), MP_ROM_PTR(&pin_PA11) }, { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA03) }, { MP_ROM_QSTR(MP_QSTR_L), MP_ROM_PTR(&pin_PA03) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA03) }, diff --git a/ports/atmel-samd/boards/capablerobot_usbhub/mpconfigboard.mk b/ports/atmel-samd/boards/capablerobot_usbhub/mpconfigboard.mk index 62399b1cdb387..42d302b0873f5 100644 --- a/ports/atmel-samd/boards/capablerobot_usbhub/mpconfigboard.mk +++ b/ports/atmel-samd/boards/capablerobot_usbhub/mpconfigboard.mk @@ -7,8 +7,7 @@ CHIP_VARIANT = SAMD51G19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q16JV_IQ" +EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q16JVxQ" LONGINT_IMPL = MPZ # No I2S on SAMD51G diff --git a/ports/atmel-samd/boards/catwan_usbstick/board.c b/ports/atmel-samd/boards/catwan_usbstick/board.c index 6baa43ffaa3cb..84960e73cf2cd 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/catwan_usbstick/mpconfigboard.mk b/ports/atmel-samd/boards/catwan_usbstick/mpconfigboard.mk index 892a5371ef29d..b1306f54b6d77 100644 --- a/ports/atmel-samd/boards/catwan_usbstick/mpconfigboard.mk +++ b/ports/atmel-samd/boards/catwan_usbstick/mpconfigboard.mk @@ -11,3 +11,5 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_ROTARYIO = 0 + +SUPEROPT_GC = 0 diff --git a/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk b/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk index 2ace30fb53457..870edb06ee021 100755 --- a/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk @@ -7,11 +7,11 @@ CHIP_VARIANT = SAMD21E18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q32JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 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/circuitbrains_deluxe_m4/mpconfigboard.mk b/ports/atmel-samd/boards/circuitbrains_deluxe_m4/mpconfigboard.mk index 13ae59de4667f..a96326c3b1653 100755 --- a/ports/atmel-samd/boards/circuitbrains_deluxe_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/circuitbrains_deluxe_m4/mpconfigboard.mk @@ -7,8 +7,7 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ, S25FL064L" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, S25FL064L" LONGINT_IMPL = MPZ CIRCUITPY_PS2IO = 1 diff --git a/ports/atmel-samd/boards/circuitplayground_express/board.c b/ports/atmel-samd/boards/circuitplayground_express/board.c index f771c214b3275..39e39b0d4bd69 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 e46e477e4e341..a32133e353973 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/mpconfigboard.mk b/ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.mk index 0b150a5fbea41..97434a90b8f73 100644 --- a/ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.mk @@ -7,11 +7,11 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ # Make room for frozen libs. +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 diff --git a/ports/atmel-samd/boards/circuitplayground_express/pins.c b/ports/atmel-samd/boards/circuitplayground_express/pins.c index 6fc46bd216b9a..1c14ee232283e 100644 --- a/ports/atmel-samd/boards/circuitplayground_express/pins.c +++ b/ports/atmel-samd/boards/circuitplayground_express/pins.c @@ -36,6 +36,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PB23) }, { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA17) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA17) }, { MP_ROM_QSTR(MP_QSTR_REMOTEIN), MP_ROM_PTR(&pin_PA12) }, diff --git a/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c b/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c index 13fed598eb397..4666482e9dbcb 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_crickit/mpconfigboard.mk b/ports/atmel-samd/boards/circuitplayground_express_crickit/mpconfigboard.mk index ae0b6837c0f5e..d6994a4c01e07 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_crickit/mpconfigboard.mk +++ b/ports/atmel-samd/boards/circuitplayground_express_crickit/mpconfigboard.mk @@ -7,12 +7,12 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C" # Turn off features and optimizations for Crickit build to make room for additional frozen libs. LONGINT_IMPL = NONE CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 @@ -22,7 +22,7 @@ CIRCUITPY_ROTARYIO = 0 CIRCUITPY_RTC = 0 SUPEROPT_GC = 0 -CFLAGS_INLINE_LIMIT = 40 +SUPEROPT_VM = 0 # Include these Python libraries in firmware. diff --git a/ports/atmel-samd/boards/circuitplayground_express_crickit/pins.c b/ports/atmel-samd/boards/circuitplayground_express_crickit/pins.c index 6fc46bd216b9a..1c14ee232283e 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_crickit/pins.c +++ b/ports/atmel-samd/boards/circuitplayground_express_crickit/pins.c @@ -36,6 +36,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PB23) }, { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA17) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA17) }, { MP_ROM_QSTR(MP_QSTR_REMOTEIN), MP_ROM_PTR(&pin_PA12) }, diff --git a/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c b/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c index 13fed598eb397..4666482e9dbcb 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/circuitplayground_express_displayio/mpconfigboard.mk b/ports/atmel-samd/boards/circuitplayground_express_displayio/mpconfigboard.mk index aace5c0cb5399..ec85666719bbc 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_displayio/mpconfigboard.mk +++ b/ports/atmel-samd/boards/circuitplayground_express_displayio/mpconfigboard.mk @@ -7,12 +7,12 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C" # Turn off features and optimizations for Crickit build to make room for additional frozen libs. LONGINT_IMPL = NONE CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 @@ -25,25 +25,10 @@ CIRCUITPY_RTC = 0 CIRCUITPY_VECTORIO = 0 SUPEROPT_GC = 0 -CFLAGS_INLINE_LIMIT = 55 +SUPEROPT_VM = 0 # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_CircuitPlayground FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_LIS3DH FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Thermistor - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), ja) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 15 -endif -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/circuitplayground_express_displayio/pins.c b/ports/atmel-samd/boards/circuitplayground_express_displayio/pins.c index 6fc46bd216b9a..1c14ee232283e 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_displayio/pins.c +++ b/ports/atmel-samd/boards/circuitplayground_express_displayio/pins.c @@ -36,6 +36,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PB23) }, { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA17) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA17) }, { MP_ROM_QSTR(MP_QSTR_REMOTEIN), MP_ROM_PTR(&pin_PA12) }, diff --git a/ports/atmel-samd/boards/cp32-m4/mpconfigboard.h b/ports/atmel-samd/boards/cp32-m4/mpconfigboard.h index 8664a6a0ecdce..bdc44c79b1b14 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/cp32-m4/mpconfigboard.mk b/ports/atmel-samd/boards/cp32-m4/mpconfigboard.mk index 6eb76c182fdcb..dfdde0dbb09c2 100644 --- a/ports/atmel-samd/boards/cp32-m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/cp32-m4/mpconfigboard.mk @@ -7,8 +7,7 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q128JV_PM" +EXTERNAL_FLASH_DEVICES = "W25Q128JVxM" # No I2S on SAMD51G. CIRCUITPY_AUDIOBUSIO = 0 diff --git a/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.h b/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.h index c67f022eb884e..b04a31c46ff83 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/mpconfigboard.mk b/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.mk index 861a0a5f7d875..3799d7ef73a30 100644 --- a/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.mk @@ -11,14 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif 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 9c69c48026902..528d989edd029 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/cp_sapling_m0_spiflash/mpconfigboard.mk b/ports/atmel-samd/boards/cp_sapling_m0_spiflash/mpconfigboard.mk index 99e13f7910a77..1a1bf8cc79b11 100644 --- a/ports/atmel-samd/boards/cp_sapling_m0_spiflash/mpconfigboard.mk +++ b/ports/atmel-samd/boards/cp_sapling_m0_spiflash/mpconfigboard.mk @@ -9,12 +9,12 @@ CHIP_FAMILY = samd21 INTERNAL_FLASH_FILESYSTEM = 0 LONGINT_IMPL = MPZ SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = AT25DF081A CIRCUITPY_AUDIOIO = 0 CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 diff --git a/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk b/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk index b1dad30eb09bf..b07f86c1602d1 100644 --- a/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk @@ -7,6 +7,5 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 3 -EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q16JV_IQ, W25Q16JV_IM" +EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q16JVxQ, W25Q16JVxM" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/datum_distance/board.c b/ports/atmel-samd/boards/datum_distance/board.c index 6baa43ffaa3cb..84960e73cf2cd 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_distance/mpconfigboard.mk b/ports/atmel-samd/boards/datum_distance/mpconfigboard.mk index ae05d32f2cf40..22b55f6fd5d3e 100644 --- a/ports/atmel-samd/boards/datum_distance/mpconfigboard.mk +++ b/ports/atmel-samd/boards/datum_distance/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/datum_imu/board.c b/ports/atmel-samd/boards/datum_imu/board.c index 6baa43ffaa3cb..84960e73cf2cd 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_imu/mpconfigboard.mk b/ports/atmel-samd/boards/datum_imu/mpconfigboard.mk index 6fd05f403bd5d..7e9918291234a 100644 --- a/ports/atmel-samd/boards/datum_imu/mpconfigboard.mk +++ b/ports/atmel-samd/boards/datum_imu/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/datum_light/board.c b/ports/atmel-samd/boards/datum_light/board.c index 6baa43ffaa3cb..84960e73cf2cd 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_light/mpconfigboard.mk b/ports/atmel-samd/boards/datum_light/mpconfigboard.mk index d42a7869de8ce..5916f23b3121d 100644 --- a/ports/atmel-samd/boards/datum_light/mpconfigboard.mk +++ b/ports/atmel-samd/boards/datum_light/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/datum_weather/board.c b/ports/atmel-samd/boards/datum_weather/board.c index 6baa43ffaa3cb..84960e73cf2cd 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/datum_weather/mpconfigboard.mk b/ports/atmel-samd/boards/datum_weather/mpconfigboard.mk index d92cbc71b3b5b..1065fb50aa472 100644 --- a/ports/atmel-samd/boards/datum_weather/mpconfigboard.mk +++ b/ports/atmel-samd/boards/datum_weather/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/dynalora_usb/board.c b/ports/atmel-samd/boards/dynalora_usb/board.c new file mode 100644 index 0000000000000..84960e73cf2cd --- /dev/null +++ b/ports/atmel-samd/boards/dynalora_usb/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/dynalora_usb/mpconfigboard.h b/ports/atmel-samd/boards/dynalora_usb/mpconfigboard.h new file mode 100644 index 0000000000000..12359ce8f6566 --- /dev/null +++ b/ports/atmel-samd/boards/dynalora_usb/mpconfigboard.h @@ -0,0 +1,36 @@ +#define MICROPY_HW_BOARD_NAME "DynaLoRa_USB" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_LED_STATUS (&pin_PA27) +#define MICROPY_HW_NEOPIXEL (&pin_PA19) + +#define SPI_FLASH_MOSI_PIN &pin_PA04 +#define SPI_FLASH_MISO_PIN &pin_PA05 +#define SPI_FLASH_SCK_PIN &pin_PA07 +#define SPI_FLASH_CS_PIN &pin_PA06 + +// These are pins not to reset. +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define DEFAULT_I2C_BUS_SCL (&pin_PA01) +#define DEFAULT_I2C_BUS_SDA (&pin_PA00) + +#define DEFAULT_SPI_BUS_SCK (&pin_PA17) +#define DEFAULT_SPI_BUS_MOSI (&pin_PA16) +#define DEFAULT_SPI_BUS_MISO (&pin_PA18) + +#define DEFAULT_UART_BUS_RX (&pin_PA00) +#define DEFAULT_UART_BUS_TX (&pin_PA01) + +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA23 1 +#define IGNORE_PIN_PA24 1 + +// Not connected +#define IGNORE_PIN_PA08 1 +#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA21 1 +#define IGNORE_PIN_PA22 1 +#define IGNORE_PIN_PA28 1 diff --git a/ports/atmel-samd/boards/dynalora_usb/mpconfigboard.mk b/ports/atmel-samd/boards/dynalora_usb/mpconfigboard.mk new file mode 100644 index 0000000000000..8b2ce7fbf4078 --- /dev/null +++ b/ports/atmel-samd/boards/dynalora_usb/mpconfigboard.mk @@ -0,0 +1,38 @@ +USB_VID = 0x04D8 +USB_PID = 0xEA2A +USB_PRODUCT = "DynaLoRa_USB" +USB_MANUFACTURER = "BHDynamics" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +SPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = GD25Q32C +LONGINT_IMPL = MPZ + +CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_FREQUENCYIO = 0 +CIRCUITPY_GAMEPAD = 0 +CIRCUITPY_DISPLAYIO = 0 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 + +CFLAGS_BOARD = --param max-inline-insns-auto=15 +ifeq ($(TRANSLATION), zh_Latn_pinyin) +RELEASE_NEEDS_CLEAN_BUILD = 1 +CFLAGS_INLINE_LIMIT = 35 +endif +ifeq ($(TRANSLATION), ja) +RELEASE_NEEDS_CLEAN_BUILD = 1 +CFLAGS_INLINE_LIMIT = 35 +endif +ifeq ($(TRANSLATION), de_DE) +RELEASE_NEEDS_CLEAN_BUILD = 1 +CFLAGS_INLINE_LIMIT = 35 +SUPEROPT_VM = 0 +endif + +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_RFM9x +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SD diff --git a/ports/atmel-samd/boards/dynalora_usb/pins.c b/ports/atmel-samd/boards/dynalora_usb/pins.c new file mode 100644 index 0000000000000..25f4985432c30 --- /dev/null +++ b/ports/atmel-samd/boards/dynalora_usb/pins.c @@ -0,0 +1,41 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PA30) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PA31) }, + + { 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_MOSI), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_RADIO_CS), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_RADIO_INT), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_RADIO_RESET), MP_ROM_PTR(&pin_PA10) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_PA03) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA00) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PA00) }, + + { MP_ROM_QSTR(MP_QSTR_MOSI1), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_MISO1), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_SCK1), MP_ROM_PTR(&pin_PA01) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_PA15) }, + + { 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/dynossat_edu_eps/board.c b/ports/atmel-samd/boards/dynossat_edu_eps/board.c index 6baa43ffaa3cb..84960e73cf2cd 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 ef4fa8f997e89..02707a69d4fbb 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_eps/mpconfigboard.mk b/ports/atmel-samd/boards/dynossat_edu_eps/mpconfigboard.mk index 303df650eb8e5..915270c57934b 100644 --- a/ports/atmel-samd/boards/dynossat_edu_eps/mpconfigboard.mk +++ b/ports/atmel-samd/boards/dynossat_edu_eps/mpconfigboard.mk @@ -8,12 +8,12 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q32C" LONGINT_IMPL = MPZ CIRCUITPY_FULLBUILD = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_I2CPERIPHERAL = 1 diff --git a/ports/atmel-samd/boards/dynossat_edu_obc/board.c b/ports/atmel-samd/boards/dynossat_edu_obc/board.c index 6baa43ffaa3cb..84960e73cf2cd 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 d7df8db74d69a..102a8cfb64e03 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/dynossat_edu_obc/mpconfigboard.mk b/ports/atmel-samd/boards/dynossat_edu_obc/mpconfigboard.mk index 360940cf18aae..8f552c5b4d18d 100644 --- a/ports/atmel-samd/boards/dynossat_edu_obc/mpconfigboard.mk +++ b/ports/atmel-samd/boards/dynossat_edu_obc/mpconfigboard.mk @@ -8,7 +8,6 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q32C" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/escornabot_makech/board.c b/ports/atmel-samd/boards/escornabot_makech/board.c index 5afe2fb655086..76849c53e4797 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/mpconfigboard.mk b/ports/atmel-samd/boards/escornabot_makech/mpconfigboard.mk index e45b5aae35f3d..ffe76d9307b70 100644 --- a/ports/atmel-samd/boards/escornabot_makech/mpconfigboard.mk +++ b/ports/atmel-samd/boards/escornabot_makech/mpconfigboard.mk @@ -12,3 +12,4 @@ CIRCUITPY_FULL_BUILD = 0 CIRCUITPY_RTC = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/escornabot_makech/pins.c b/ports/atmel-samd/boards/escornabot_makech/pins.c index fefee191993df..86a70cb041b03 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 6baa43ffaa3cb..84960e73cf2cd 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_adalogger/mpconfigboard.h b/ports/atmel-samd/boards/feather_m0_adalogger/mpconfigboard.h index a0fde67ef6a51..704c0552d3a16 100644 --- a/ports/atmel-samd/boards/feather_m0_adalogger/mpconfigboard.h +++ b/ports/atmel-samd/boards/feather_m0_adalogger/mpconfigboard.h @@ -8,8 +8,8 @@ #define MICROPY_PORT_B (0) #define MICROPY_PORT_C (0) -#define DEFAULT_I2C_BUS_SCL (&pin_PA22) -#define DEFAULT_I2C_BUS_SDA (&pin_PA23) +#define DEFAULT_I2C_BUS_SDA (&pin_PA22) +#define DEFAULT_I2C_BUS_SCL (&pin_PA23) #define DEFAULT_SPI_BUS_SCK (&pin_PB11) #define DEFAULT_SPI_BUS_MOSI (&pin_PB10) diff --git a/ports/atmel-samd/boards/feather_m0_basic/board.c b/ports/atmel-samd/boards/feather_m0_basic/board.c index 6baa43ffaa3cb..84960e73cf2cd 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_basic/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m0_basic/mpconfigboard.mk index 69ebdfc237244..183a80ffa4340 100644 --- a/ports/atmel-samd/boards/feather_m0_basic/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_basic/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/feather_m0_express/board.c b/ports/atmel-samd/boards/feather_m0_express/board.c index 6baa43ffaa3cb..84960e73cf2cd 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 5421dc88901e8..27ea6c72bae71 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/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.mk index d1a6fc7ae5a0c..fcf1b4a1aa4ef 100644 --- a/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.mk @@ -7,11 +7,11 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 @@ -19,20 +19,5 @@ CIRCUITPY_MSGPACK = 0 CIRCUITPY_VECTORIO = 0 CIRCUITPY_BUSDEVICE = 0 -CFLAGS_INLINE_LIMIT = 60 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), ja) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif 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 6baa43ffaa3cb..84960e73cf2cd 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 ee61e1d87d6d7..112dd80fa6b8b 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_express_crickit/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m0_express_crickit/mpconfigboard.mk index 309563ff4998c..e29f3c0b290e4 100644 --- a/ports/atmel-samd/boards/feather_m0_express_crickit/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_express_crickit/mpconfigboard.mk @@ -7,12 +7,12 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ # Make space for frozen libs CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 diff --git a/ports/atmel-samd/boards/feather_m0_rfm69/board.c b/ports/atmel-samd/boards/feather_m0_rfm69/board.c index 6baa43ffaa3cb..84960e73cf2cd 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_rfm69/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m0_rfm69/mpconfigboard.mk index 6ea21ed82e824..b544a3680a9fa 100644 --- a/ports/atmel-samd/boards/feather_m0_rfm69/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_rfm69/mpconfigboard.mk @@ -13,6 +13,7 @@ CIRCUITPY_FULL_BUILD = 0 # A number of modules are removed for RFM69 to make room for frozen libraries. # Many I/O functions are not available. CIRCUITPY_ANALOGIO = 1 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_PULSEIO = 0 CIRCUITPY_NEOPIXEL_WRITE = 1 CIRCUITPY_ROTARYIO = 0 diff --git a/ports/atmel-samd/boards/feather_m0_rfm9x/board.c b/ports/atmel-samd/boards/feather_m0_rfm9x/board.c index 6baa43ffaa3cb..84960e73cf2cd 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_rfm9x/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m0_rfm9x/mpconfigboard.mk index 76a6be2e34e28..e307ab4f6b992 100644 --- a/ports/atmel-samd/boards/feather_m0_rfm9x/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_rfm9x/mpconfigboard.mk @@ -14,6 +14,7 @@ CIRCUITPY_FULL_BUILD = 0 # A number of modules are removed for RFM9x to make room for frozen libraries. # Many I/O functions are not available. CIRCUITPY_ANALOGIO = 1 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_PULSEIO = 0 CIRCUITPY_NEOPIXEL_WRITE = 1 CIRCUITPY_ROTARYIO = 0 diff --git a/ports/atmel-samd/boards/feather_m0_supersized/board.c b/ports/atmel-samd/boards/feather_m0_supersized/board.c index 6baa43ffaa3cb..84960e73cf2cd 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 2d9f88e2e1651..9fa2ba9ce7b8e 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_m0_supersized/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.mk index 3078544fcba8c..dd012cb487cbd 100644 --- a/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.mk @@ -7,11 +7,11 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "S25FL064L" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 diff --git a/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk index 345ac33c5dd69..4c0c5137c155b 100644 --- a/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAME51J19A CHIP_FAMILY = same51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk index 4946788d3e129..a8b4460a6ecde 100644 --- a/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk @@ -7,8 +7,8 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ CIRCUITPY_VECTORIO = 1 +CIRCUITPY__EVE = 1 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 6baa43ffaa3cb..84960e73cf2cd --- 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 2afe35817806f..b1839f2c99d58 --- 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/feather_radiofruit_zigbee/mpconfigboard.mk b/ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.mk index 9f9bb0501edf7..29774db742c27 100755 --- a/ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMR21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ @@ -16,6 +15,7 @@ CIRCUITPY_AUDIOBUSIO = 0 # No DAC on SAMR21G CIRCUITPY_AUDIOIO = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_RTC = 0 CIRCUITPY_FREQUENCYIO = 0 diff --git a/ports/atmel-samd/boards/fluff_m0/board.c b/ports/atmel-samd/boards/fluff_m0/board.c index 6baa43ffaa3cb..84960e73cf2cd 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/fluff_m0/mpconfigboard.mk b/ports/atmel-samd/boards/fluff_m0/mpconfigboard.mk index c040eb430480e..52fcaec02009f 100644 --- a/ports/atmel-samd/boards/fluff_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/fluff_m0/mpconfigboard.mk @@ -11,9 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/gemma_m0/board.c b/ports/atmel-samd/boards/gemma_m0/board.c index 6baa43ffaa3cb..84960e73cf2cd 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/gemma_m0/mpconfigboard.mk b/ports/atmel-samd/boards/gemma_m0/mpconfigboard.mk index e1c0f4b9a7080..9d086c8f595d2 100644 --- a/ports/atmel-samd/boards/gemma_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/gemma_m0/mpconfigboard.mk @@ -11,14 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/gemma_m0/pins.c b/ports/atmel-samd/boards/gemma_m0/pins.c index 9aecd5d84e32e..63e2ec54a08b3 100644 --- a/ports/atmel-samd/boards/gemma_m0/pins.c +++ b/ports/atmel-samd/boards/gemma_m0/pins.c @@ -14,6 +14,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA02) }, { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA23) }, { MP_ROM_QSTR(MP_QSTR_L), MP_ROM_PTR(&pin_PA23) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA23) }, diff --git a/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.h b/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.h index bab0550148086..f2f3d7cc46bfa 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/grandcentral_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.mk index 08eb5c98bae4f..6d9ecff636ca5 100644 --- a/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.mk @@ -7,8 +7,8 @@ CHIP_VARIANT = SAMD51P20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ, GD25Q64C" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, GD25Q64C" LONGINT_IMPL = MPZ CIRCUITPY_SDIOIO = 1 +CIRCUITPY_IMAGECAPTURE = 1 diff --git a/ports/atmel-samd/boards/hallowing_m0_express/board.c b/ports/atmel-samd/boards/hallowing_m0_express/board.c index 8b922d6bef7fd..a9c11f1bae357 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 e5ac346daf4e5..28ce10811902d 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_m0_express/mpconfigboard.mk b/ports/atmel-samd/boards/hallowing_m0_express/mpconfigboard.mk index 2b211abd4e06d..8c513154296d4 100644 --- a/ports/atmel-samd/boards/hallowing_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/hallowing_m0_express/mpconfigboard.mk @@ -7,8 +7,7 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ, GD25Q64C" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, GD25Q64C" LONGINT_IMPL = NONE # To keep the build small @@ -25,22 +24,8 @@ CIRCUITPY_VECTORIO = 0 CFLAGS_INLINE_LIMIT = 55 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_LIS3DH FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), ja) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/hallowing_m4_express/board.c b/ports/atmel-samd/boards/hallowing_m4_express/board.c index f51d4282d3fbc..f9cdbdbafb3ae 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/hallowing_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/hallowing_m4_express/mpconfigboard.mk index 4bf1552884aa3..1154d0bb1f3a6 100644 --- a/ports/atmel-samd/boards/hallowing_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/hallowing_m4_express/mpconfigboard.mk @@ -7,6 +7,5 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q64C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/huntercat_nfc/board.c b/ports/atmel-samd/boards/huntercat_nfc/board.c new file mode 100644 index 0000000000000..84960e73cf2cd --- /dev/null +++ b/ports/atmel-samd/boards/huntercat_nfc/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.h b/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.h new file mode 100644 index 0000000000000..3be98beb38899 --- /dev/null +++ b/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.h @@ -0,0 +1,53 @@ +#define MICROPY_HW_BOARD_NAME "Electronic Cats Hunter Cat NFC" +#define MICROPY_HW_MCU_NAME "samd21e18" + +#define MICROPY_HW_LED_STATUS (&pin_PA00) + +#define SPI_FLASH_MOSI_PIN &pin_PA18 +#define SPI_FLASH_MISO_PIN &pin_PA22 +#define SPI_FLASH_SCK_PIN &pin_PA19 +#define SPI_FLASH_CS_PIN &pin_PA17 + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define CALIBRATE_CRYSTALLESS 1 + +#define DEFAULT_I2C_BUS_SCL (&pin_PA08) +#define DEFAULT_I2C_BUS_SDA (&pin_PA09) + +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA06 1 +#define IGNORE_PIN_PA20 1 +#define IGNORE_PIN_PA21 1 +#define IGNORE_PIN_PA23 1 +#define IGNORE_PIN_PA28 1 +// USB is always used. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 +#define IGNORE_PIN_PA30 1 +#define IGNORE_PIN_PA31 1 +#define IGNORE_PIN_PB01 1 +#define IGNORE_PIN_PB02 1 +#define IGNORE_PIN_PB03 1 +#define IGNORE_PIN_PB04 1 +#define IGNORE_PIN_PB05 1 +#define IGNORE_PIN_PB06 1 +#define IGNORE_PIN_PB07 1 +#define IGNORE_PIN_PB08 1 +#define IGNORE_PIN_PB09 1 +#define IGNORE_PIN_PB10 1 +#define IGNORE_PIN_PB11 1 +#define IGNORE_PIN_PB12 1 +#define IGNORE_PIN_PB13 1 +#define IGNORE_PIN_PB14 1 +#define IGNORE_PIN_PB15 1 +#define IGNORE_PIN_PB16 1 +#define IGNORE_PIN_PB17 1 +#define IGNORE_PIN_PB22 1 +#define IGNORE_PIN_PB23 1 +#define IGNORE_PIN_PB30 1 +#define IGNORE_PIN_PB31 1 +#define IGNORE_PIN_PB00 1 diff --git a/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.mk b/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.mk new file mode 100644 index 0000000000000..43a0d38d7df64 --- /dev/null +++ b/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.mk @@ -0,0 +1,25 @@ +USB_VID = 0x1209 +USB_PID = 0x7150 +USB_PRODUCT = "Hunter Cat NFC" +USB_MANUFACTURER = "Electronic Cats" + +CHIP_VARIANT = SAMD21E18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 0 +SPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" +LONGINT_IMPL = MPZ + +CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 +CIRCUITPY_NEOPIXEL_WRITE = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_TOUCHIO = 0 +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/huntercat_nfc/pins.c b/ports/atmel-samd/boards/huntercat_nfc/pins.c new file mode 100644 index 0000000000000..12b0d9348062b --- /dev/null +++ b/ports/atmel-samd/boards/huntercat_nfc/pins.c @@ -0,0 +1,30 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PA22) }, + { 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_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk b/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk index 0c0d6053e4c4e..467c6af47af9e 100644 --- a/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "W25Q16FW, GD25Q16C" LONGINT_IMPL = MPZ @@ -15,6 +14,7 @@ CIRCUITPY_BITBANG_APA102 = 1 CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_GAMEPAD = 0 diff --git a/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk index eb02d3c2705f9..7a45ef21e9d80 100644 --- a/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51G19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.h b/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.h index 4d911ad64c1e7..0ac595edf7718 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/mpconfigboard.mk b/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.mk index 2492651516fff..ea010ed2ee140 100644 --- a/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.mk +++ b/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.mk @@ -12,6 +12,7 @@ LONGINT_IMPL = MPZ # Not needed. CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_AUDIOMP3 = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_BLEIO_HCI = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 diff --git a/ports/atmel-samd/boards/kicksat-sprite/pins.c b/ports/atmel-samd/boards/kicksat-sprite/pins.c index 27ee90323121d..711406189d6db 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/matrixportal_m4/mpconfigboard.mk b/ports/atmel-samd/boards/matrixportal_m4/mpconfigboard.mk index 44b28acbcb913..41e24f1995ce3 100644 --- a/ports/atmel-samd/boards/matrixportal_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/matrixportal_m4/mpconfigboard.mk @@ -7,6 +7,5 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 3 EXTERNAL_FLASH_DEVICES = "S25FL116K, S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/meowmeow/board.c b/ports/atmel-samd/boards/meowmeow/board.c index 5afe2fb655086..76849c53e4797 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/meowmeow/mpconfigboard.mk b/ports/atmel-samd/boards/meowmeow/mpconfigboard.mk index 175501313e04b..8ee9d23fe5bfe 100644 --- a/ports/atmel-samd/boards/meowmeow/mpconfigboard.mk +++ b/ports/atmel-samd/boards/meowmeow/mpconfigboard.mk @@ -14,3 +14,4 @@ CIRCUITPY_COUNTIO = 0 CIRCUITPY_RTC = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/metro_m0_express/board.c b/ports/atmel-samd/boards/metro_m0_express/board.c index bb1c5335c18af..bb6ad8bc0dbc0 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/metro_m0_express/mpconfigboard.mk b/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.mk index 03f633e6d855e..964d33553769d 100644 --- a/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.mk @@ -7,31 +7,16 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_MSGPACK = 0 CIRCUITPY_VECTORIO = 0 CIRCUITPY_BUSDEVICE = 0 -CFLAGS_INLINE_LIMIT = 60 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), ja) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/metro_m4_airlift_lite/mpconfigboard.mk b/ports/atmel-samd/boards/metro_m4_airlift_lite/mpconfigboard.mk index 58d4e49805c04..1e63476596207 100644 --- a/ports/atmel-samd/boards/metro_m4_airlift_lite/mpconfigboard.mk +++ b/ports/atmel-samd/boards/metro_m4_airlift_lite/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 3 EXTERNAL_FLASH_DEVICES = "S25FL116K, S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk index c2603002cd700..553bf14f2eaf0 100644 --- a/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 3 EXTERNAL_FLASH_DEVICES = "S25FL116K, S25FL216K, GD25Q16C" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk b/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk index 321ee5f476adf..c3e21a4c362a8 100644 --- a/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk @@ -7,8 +7,7 @@ CHIP_VARIANT = SAMD51G19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "W25Q16JV_IM, W25Q16JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q16JVxM, W25Q16JVxQ" LONGINT_IMPL = MPZ # No I2S on SAMD51G diff --git a/ports/atmel-samd/boards/monster_m4sk/board.c b/ports/atmel-samd/boards/monster_m4sk/board.c index 2b757d0914e21..8ef0c6ff95b1f 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/monster_m4sk/mpconfigboard.mk b/ports/atmel-samd/boards/monster_m4sk/mpconfigboard.mk index 9b242a3ffca3a..86a04be87f2cd 100644 --- a/ports/atmel-samd/boards/monster_m4sk/mpconfigboard.mk +++ b/ports/atmel-samd/boards/monster_m4sk/mpconfigboard.mk @@ -7,6 +7,5 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q64C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/ndgarage_ndbit6/mpconfigboard.mk b/ports/atmel-samd/boards/ndgarage_ndbit6/mpconfigboard.mk index 09804bc4e7299..3882e780eb52a 100644 --- a/ports/atmel-samd/boards/ndgarage_ndbit6/mpconfigboard.mk +++ b/ports/atmel-samd/boards/ndgarage_ndbit6/mpconfigboard.mk @@ -12,3 +12,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/ndgarage_ndbit6_v2/mpconfigboard.mk b/ports/atmel-samd/boards/ndgarage_ndbit6_v2/mpconfigboard.mk index 193a0cf991046..4ae1d8741d96e 100644 --- a/ports/atmel-samd/boards/ndgarage_ndbit6_v2/mpconfigboard.mk +++ b/ports/atmel-samd/boards/ndgarage_ndbit6_v2/mpconfigboard.mk @@ -12,3 +12,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk index ab8065a9c5865..0f90dba6a1cd5 100644 --- a/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/neopixel_trinkey_m0/mpconfigboard.mk @@ -9,8 +9,6 @@ CHIP_FAMILY = samd21 INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = NONE -SUPEROPT_GC = 0 - CIRCUITPY_ANALOGIO = 0 CIRCUITPY_ROTARYIO = 0 CIRCUITPY_RTC = 0 @@ -20,7 +18,7 @@ CIRCUITPY_PULSEIO = 0 CIRCUITPY_PWMIO = 0 CIRCUITPY_AUDIOCORE = 0 CIRCUITPY_BUSIO = 0 -CIRCUITPY_STORAGE = 0 +CIRCUITPY_STORAGE = 1 CIRCUITPY_MATH = 1 CIRCUITPY_PIXELBUF = 1 @@ -28,16 +26,8 @@ CIRCUITPY_USB_MIDI = 1 CIRCUITPY_TOUCHIO = 1 CIRCUITPY_FULL_BUILD = 0 -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 +SUPEROPT_GC = 0 SUPEROPT_VM = 0 -endif # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/atmel-samd/boards/nfc_copy_cat/board.c b/ports/atmel-samd/boards/nfc_copy_cat/board.c index 6baa43ffaa3cb..84960e73cf2cd 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/nfc_copy_cat/mpconfigboard.mk b/ports/atmel-samd/boards/nfc_copy_cat/mpconfigboard.mk index 1b4a16a08d61a..eb7a87feaff16 100644 --- a/ports/atmel-samd/boards/nfc_copy_cat/mpconfigboard.mk +++ b/ports/atmel-samd/boards/nfc_copy_cat/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD21E18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" LONGINT_IMPL = NONE diff --git a/ports/atmel-samd/boards/openbook_m4/board.c b/ports/atmel-samd/boards/openbook_m4/board.c index a110779a6a733..d8184da73e819 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/openbook_m4/mpconfigboard.mk b/ports/atmel-samd/boards/openbook_m4/mpconfigboard.mk index e5fa0cd84b70f..85b2dd42053f6 100644 --- a/ports/atmel-samd/boards/openbook_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/openbook_m4/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/pewpew10/mpconfigboard.mk b/ports/atmel-samd/boards/pewpew10/mpconfigboard.mk index fadcc21448fe3..8b2ac7ff78234 100644 --- a/ports/atmel-samd/boards/pewpew10/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pewpew10/mpconfigboard.mk @@ -20,12 +20,6 @@ CIRCUITPY_SAMD = 0 CIRCUITPY_USB_MIDI = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 FROZEN_MPY_DIRS += $(TOP)/frozen/pew-pewpew-standalone-10.x - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/pewpew_m4/board.c b/ports/atmel-samd/boards/pewpew_m4/board.c index 26bd53cad1049..88c5bd9698d76 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/pewpew_m4/mpconfigboard.mk b/ports/atmel-samd/boards/pewpew_m4/mpconfigboard.mk index 1614779684113..99dddfa892d3e 100644 --- a/ports/atmel-samd/boards/pewpew_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pewpew_m4/mpconfigboard.mk @@ -25,6 +25,7 @@ CIRCUITPY_ROTARYIO = 0 CIRCUITPY_RTC = 0 CIRCUITPY_SAMD = 0 CIRCUITPY_TOUCHIO = 0 +CIRCUIPTY_USB_CDC = 0 CIRCUITPY_USB_HID = 0 CIRCUITPY_USB_MIDI = 0 CIRCUITPY_VECTORIO = 0 @@ -40,12 +41,5 @@ CIRCUITPY_STAGE = 1 FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-stage/pewpew_m4 CIRCUITPY_DISPLAY_FONT = $(TOP)/ports/atmel-samd/boards/ugame10/brutalist-6.bdf -# Tweak inlining depending on language. -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 45 -else -CFLAGS_INLINE_LIMIT = 70 -endif # Override optimization to keep binary small OPTIMIZATION_FLAGS = -Os diff --git a/ports/atmel-samd/boards/picoplanet/mpconfigboard.h b/ports/atmel-samd/boards/picoplanet/mpconfigboard.h index 61430e06c2ea9..30a9169e04339 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/picoplanet/mpconfigboard.mk b/ports/atmel-samd/boards/picoplanet/mpconfigboard.mk index da97b90cc254d..e931553747601 100644 --- a/ports/atmel-samd/boards/picoplanet/mpconfigboard.mk +++ b/ports/atmel-samd/boards/picoplanet/mpconfigboard.mk @@ -11,14 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/pirkey_m0/board.c b/ports/atmel-samd/boards/pirkey_m0/board.c index 6baa43ffaa3cb..84960e73cf2cd 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/pirkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.mk index 8b7066ac7a87a..b8ae7792165a2 100644 --- a/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pirkey_m0/mpconfigboard.mk @@ -21,12 +21,11 @@ CIRCUITPY_SAMD = 0 CIRCUITPY_USB_MIDI = 1 CIRCUITPY_TOUCHIO = 0 CIRCUITPY_FULL_BUILD = 0 -# Make more room. + SUPEROPT_GC = 0 +SUPEROPT_VM = 0 # Include these Python libraries in firmware. # FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DotStar FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_IRRemote - -CFLAGS_BOARD = --param max-inline-insns-auto=12 diff --git a/ports/atmel-samd/boards/pybadge/board.c b/ports/atmel-samd/boards/pybadge/board.c index 188bf7bf6c769..4adf10710ee59 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/mpconfigboard.mk b/ports/atmel-samd/boards/pybadge/mpconfigboard.mk index 7a213faf4c3f2..54f00b7448276 100644 --- a/ports/atmel-samd/boards/pybadge/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pybadge/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/pybadge_airlift/board.c b/ports/atmel-samd/boards/pybadge_airlift/board.c index de7eeda09679e..fe3549a64ab04 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/mpconfigboard.mk b/ports/atmel-samd/boards/pybadge_airlift/mpconfigboard.mk index 5ae09294d698f..a88e5e5e5b378 100644 --- a/ports/atmel-samd/boards/pybadge_airlift/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pybadge_airlift/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/pybadge_airlift/pins.c b/ports/atmel-samd/boards/pybadge_airlift/pins.c index cdf8071da8908..cce9b044209ed 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 f092a8d20e5d1..2777b9031cb13 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 fc16e22b59b4d..244f41da38f8d 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/mpconfigboard.mk b/ports/atmel-samd/boards/pycubed/mpconfigboard.mk index a82362b8d2c3d..1eb3cd52396d7 100644 --- a/ports/atmel-samd/boards/pycubed/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pycubed/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = W25Q80DV LONGINT_IMPL = MPZ @@ -15,6 +14,7 @@ CIRCUITPY_DRIVE_LABEL = "PYCUBED" # Not needed. CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_GAMEPAD = 0 diff --git a/ports/atmel-samd/boards/pycubed_mram/board.c b/ports/atmel-samd/boards/pycubed_mram/board.c index f092a8d20e5d1..2777b9031cb13 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 e2a733025d9db..0d49e1b00f77f 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/pycubed_mram/mpconfigboard.mk b/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.mk index 3bf42d70543b6..0c459c309c87c 100644 --- a/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = MR2xH40 LONGINT_IMPL = MPZ @@ -15,6 +14,7 @@ CIRCUITPY_DRIVE_LABEL = "PYCUBED" # Not needed. CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_GAMEPAD = 0 diff --git a/ports/atmel-samd/boards/pygamer/board.c b/ports/atmel-samd/boards/pygamer/board.c index 4614e347cd45d..11e18f127138c 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/mpconfigboard.mk b/ports/atmel-samd/boards/pygamer/mpconfigboard.mk index 2db6786bfdf17..5cef7b44cf94e 100644 --- a/ports/atmel-samd/boards/pygamer/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pygamer/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q64C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/pygamer_advance/board.c b/ports/atmel-samd/boards/pygamer_advance/board.c index 39bf65602e27e..0711c4298aea0 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/pygamer_advance/mpconfigboard.mk b/ports/atmel-samd/boards/pygamer_advance/mpconfigboard.mk index d001374a50144..a58e016542d3b 100644 --- a/ports/atmel-samd/boards/pygamer_advance/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pygamer_advance/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q64C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/pyportal/board.c b/ports/atmel-samd/boards/pyportal/board.c index db474a8209735..abeeab8e79681 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 @@ -69,9 +69,10 @@ void board_init(void) { &pin_PB06, // Chip select &pin_PB09, // Write &pin_PB04, // Read - &pin_PA00); // Reset + &pin_PA00, // Reset + 0); // Frequency - 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 00c376ad90bd5..351647b1223e6 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/mpconfigboard.mk b/ports/atmel-samd/boards/pyportal/mpconfigboard.mk index 149141a4e30d1..0a70db50c996d 100644 --- a/ports/atmel-samd/boards/pyportal/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pyportal/mpconfigboard.mk @@ -7,6 +7,5 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ, GD25Q64C" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, GD25Q64C" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/pyportal_titano/board.c b/ports/atmel-samd/boards/pyportal_titano/board.c index 59a25c4acfbd4..e2b231980b8d9 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 @@ -86,9 +86,10 @@ void board_init(void) { &pin_PB06, // Chip select &pin_PB09, // Write &pin_PB04, // Read - &pin_PA00); // Reset + &pin_PA00, // Reset + 0); // Frequency - 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 a76f1db5c846b..61c6117d967ed 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/pyportal_titano/mpconfigboard.mk b/ports/atmel-samd/boards/pyportal_titano/mpconfigboard.mk index dbc2d5ae996a2..2202fca2f702c 100644 --- a/ports/atmel-samd/boards/pyportal_titano/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pyportal_titano/mpconfigboard.mk @@ -7,6 +7,5 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ, GD25Q64C" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, GD25Q64C" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/pyruler/mpconfigboard.mk b/ports/atmel-samd/boards/pyruler/mpconfigboard.mk index 4484b4ed94949..1a73ade94d702 100644 --- a/ports/atmel-samd/boards/pyruler/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pyruler/mpconfigboard.mk @@ -11,10 +11,6 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_RTC = 0 -SUPEROPT_GC = 0 -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/qtpy_m0/mpconfigboard.mk b/ports/atmel-samd/boards/qtpy_m0/mpconfigboard.mk index e100e2da6230c..c214006eade6c 100644 --- a/ports/atmel-samd/boards/qtpy_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/qtpy_m0/mpconfigboard.mk @@ -12,5 +12,3 @@ CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 SUPEROPT_VM = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 diff --git a/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk b/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk index 8773c5771dd94..a88bea91de1f9 100644 --- a/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk +++ b/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk @@ -9,25 +9,15 @@ CHIP_FAMILY = samd21 INTERNAL_FLASH_FILESYSTEM = 0 LONGINT_IMPL = MPZ SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_MSGPACK = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.h b/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.h index c66873aeb27fe..4e482cff5a714 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/mpconfigboard.mk b/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.mk index fd6e25f6cb7d0..0ae092c6931b6 100644 --- a/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.mk @@ -9,13 +9,13 @@ CHIP_FAMILY = samd51 #QSPI_FLASH_FILESYSTEM = 0 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" LONGINT_IMPL = MPZ # No I2S on SAMD51G CIRCUITPY_AUDIOBUSIO = 0 # Make room for more stuff +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_FREQUENCYIO = 0 diff --git a/ports/atmel-samd/boards/robohatmm1_m4/pins.c b/ports/atmel-samd/boards/robohatmm1_m4/pins.c index 74dcfd651f88a..32959ef3f2903 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 364d380d1d832..19f326782a38d 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 934559a2a4d15..dbdd1aaa6a483 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/same54_xplained/mpconfigboard.mk b/ports/atmel-samd/boards/same54_xplained/mpconfigboard.mk index e4472e05d619a..53aac7df2a30e 100644 --- a/ports/atmel-samd/boards/same54_xplained/mpconfigboard.mk +++ b/ports/atmel-samd/boards/same54_xplained/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAME54P20A CHIP_FAMILY = same54 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "N25Q256A" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c b/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c index 53c43cd441bb4..fe2393a572d23 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/mpconfigboard.mk b/ports/atmel-samd/boards/seeeduino_wio_terminal/mpconfigboard.mk index f57e016b4e3b1..9788f5ff40016 100644 --- a/ports/atmel-samd/boards/seeeduino_wio_terminal/mpconfigboard.mk +++ b/ports/atmel-samd/boards/seeeduino_wio_terminal/mpconfigboard.mk @@ -7,8 +7,7 @@ CHIP_VARIANT = SAMD51P19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q32JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" LONGINT_IMPL = MPZ CIRCUITPY_VECTORIO = 1 diff --git a/ports/atmel-samd/boards/seeeduino_wio_terminal/pins.c b/ports/atmel-samd/boards/seeeduino_wio_terminal/pins.c index 0558191e637ce..8d9c76164e03d 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 @@ -60,7 +60,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_PC16) }, { MP_OBJ_NEW_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_PC17) }, { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_PC19) }, - { MP_ROM_QSTR(MP_QSTR_SD_DET), MP_ROM_PTR(&pin_PC21) }, + { MP_ROM_QSTR(MP_QSTR_SD_DET), MP_ROM_PTR(&pin_PD21) }, // Switch { MP_OBJ_NEW_QSTR(MP_QSTR_SWITCH_UP), MP_ROM_PTR(&pin_PD20) }, diff --git a/ports/atmel-samd/boards/seeeduino_xiao/mpconfigboard.mk b/ports/atmel-samd/boards/seeeduino_xiao/mpconfigboard.mk index bedec87f454c8..6bbd84235a712 100644 --- a/ports/atmel-samd/boards/seeeduino_xiao/mpconfigboard.mk +++ b/ports/atmel-samd/boards/seeeduino_xiao/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/sensebox_mcu/board.c b/ports/atmel-samd/boards/sensebox_mcu/board.c new file mode 100644 index 0000000000000..7af05ba45a53e --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/board.c @@ -0,0 +1,39 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "hal/include/hal_gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.h b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.h new file mode 100644 index 0000000000000..13aca289f6584 --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.h @@ -0,0 +1,24 @@ +#define MICROPY_HW_BOARD_NAME "senseBox MCU" +#define MICROPY_HW_MCU_NAME "senseBox" + +#define MICROPY_HW_LED_STATUS (&pin_PA27) + +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) + +#define DEFAULT_I2C_BUS_SCL (&pin_PA09) +#define DEFAULT_I2C_BUS_SDA (&pin_PA08) + +#define DEFAULT_SPI_BUS_SCK (&pin_PA17) +#define DEFAULT_SPI_BUS_MOSI (&pin_PA16) +#define DEFAULT_SPI_BUS_MISO (&pin_PA19) + +#define DEFAULT_UART_BUS_RX (&pin_PA23) +#define DEFAULT_UART_BUS_TX (&pin_PA22) + +#define SAMD21_BOD33_LEVEL (6) + +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 diff --git a/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.mk b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.mk new file mode 100644 index 0000000000000..f5ce4a5d13344 --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x04D8 +USB_PID = 0xEF67 +USB_PRODUCT = "senseBox MCU" +USB_MANUFACTURER = "senseBox" + +CHIP_VARIANT = SAMD21G18A +CHIP_FAMILY = samd21 + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE +CIRCUITPY_FULL_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/sensebox_mcu/pins.c b/ports/atmel-samd/boards/sensebox_mcu/pins.c new file mode 100644 index 0000000000000..55afcc989e465 --- /dev/null +++ b/ports/atmel-samd/boards/sensebox_mcu/pins.c @@ -0,0 +1,71 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + + // Analog pins + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PA02) }, + + // Digital pins + // { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PA20) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PA28) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PB09) }, + + // UART pins + { MP_ROM_QSTR(MP_QSTR_UART_PWR), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_TX2), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_RX2), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PA22) }, // alias of TX1 + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PA23) }, // alias of RX1 + + // SPI pins + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PA19) }, + + // I2C pins + { MP_ROM_QSTR(MP_QSTR_I2C_PWR), MP_ROM_PTR(&pin_PB11) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA08) }, + + // LED pins + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_RED_LED), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_GREEN_LED), MP_ROM_PTR(&pin_PA28) }, + + // XBEE pins + { MP_ROM_QSTR(MP_QSTR_XB1_PWR), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_XB2_PWR), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_XB1_CS), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_XB2_CS), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_XB1_INT), MP_ROM_PTR(&pin_PA21) }, + { MP_ROM_QSTR(MP_QSTR_XB2_INT), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_XB1_RX), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_XB1_TX), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_XB2_RX), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_XB2_TX), MP_ROM_PTR(&pin_PA10) }, + + + // Comm objects + { 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/serpente/mpconfigboard.mk b/ports/atmel-samd/boards/serpente/mpconfigboard.mk index 09036875f16cc..32ba32f386fe6 100644 --- a/ports/atmel-samd/boards/serpente/mpconfigboard.mk +++ b/ports/atmel-samd/boards/serpente/mpconfigboard.mk @@ -7,28 +7,14 @@ CHIP_VARIANT = SAMD21E18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q32C LONGINT_IMPL = NONE CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_GAMEPAD = 0 CIRCUITPY_BUSDEVICE = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), ja) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/shirtty/mpconfigboard.mk b/ports/atmel-samd/boards/shirtty/mpconfigboard.mk index 0b56e9ae02cc8..70fe447232e0f 100644 --- a/ports/atmel-samd/boards/shirtty/mpconfigboard.mk +++ b/ports/atmel-samd/boards/shirtty/mpconfigboard.mk @@ -13,5 +13,4 @@ CIRCUITPY_I2CPERIPHERAL = 1 CIRCUITPY_TOUCHIO = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk b/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk index bf88cd52d0080..e64045f13a76a 100644 --- a/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk +++ b/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/snekboard/board.c b/ports/atmel-samd/boards/snekboard/board.c index 6baa43ffaa3cb..84960e73cf2cd 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 1c0804fe72042..bea90a0faefc1 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/snekboard/mpconfigboard.mk b/ports/atmel-samd/boards/snekboard/mpconfigboard.mk index 889490450f28d..3467ef75789ca 100644 --- a/ports/atmel-samd/boards/snekboard/mpconfigboard.mk +++ b/ports/atmel-samd/boards/snekboard/mpconfigboard.mk @@ -7,11 +7,11 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q16JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_GAMEPAD = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_MSGPACK = 0 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 6baa43ffaa3cb..84960e73cf2cd --- 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 80f37429fa595..836261bf8d76b --- 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_lumidrive/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.mk index 2e15bc042ac3c..197dea6fe2059 100755 --- a/ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.mk @@ -7,12 +7,12 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "W25Q32FV" LONGINT_IMPL = MPZ CIRCUITPY_AUDIOIO = 0 CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_VECTORIO = 0 CIRCUITPY_BUSDEVICE = 0 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 6baa43ffaa3cb..84960e73cf2cd 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 dcce97b8da990..c2527301ffa8e 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_no_flash/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/mpconfigboard.mk index 22e2059a9316f..435ee87fde694 100644 --- a/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/mpconfigboard.mk @@ -10,4 +10,6 @@ INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 + SUPEROPT_GC = 0 +SUPEROPT_VM = 0 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 6baa43ffaa3cb..84960e73cf2cd 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 c9b195eef439a..4fb43629b4035 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_qwiic_micro_with_flash/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/mpconfigboard.mk index dd01c9985b924..7c2fd57ea1b2c 100644 --- a/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD21E18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "W25Q32FV" LONGINT_IMPL = MPZ 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 6baa43ffaa3cb..84960e73cf2cd --- 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 ae272d502bd8e..b4076523f431d --- 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/sparkfun_redboard_turbo/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.mk index 5b7f93328de97..a5cd49239eca7 100755 --- a/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.mk @@ -7,11 +7,11 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "W25Q32FV" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_GAMEPAD = 0 CIRCUITPY_I2CPERIPHERAL = 0 diff --git a/ports/atmel-samd/boards/sparkfun_samd21_dev/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_samd21_dev/mpconfigboard.mk index 3104be0a0fd96..bafcc02a2b8c8 100644 --- a/ports/atmel-samd/boards/sparkfun_samd21_dev/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_samd21_dev/mpconfigboard.mk @@ -10,10 +10,5 @@ INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 -ifeq ($(TRANSLATION),de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif - SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/sparkfun_samd21_mini/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_samd21_mini/mpconfigboard.mk index 9460d0009b2e6..aef38661be4a3 100644 --- a/ports/atmel-samd/boards/sparkfun_samd21_mini/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_samd21_mini/mpconfigboard.mk @@ -11,3 +11,4 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/sparkfun_samd51_thing_plus/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_samd51_thing_plus/mpconfigboard.mk index 567f1db205a42..e33035d949a8d 100644 --- a/ports/atmel-samd/boards/sparkfun_samd51_thing_plus/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_samd51_thing_plus/mpconfigboard.mk @@ -8,7 +8,6 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = AT25SF041A LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/stackrduino_m0_pro/mpconfigboard.mk b/ports/atmel-samd/boards/stackrduino_m0_pro/mpconfigboard.mk index 734be2d145d86..fb46e99dae320 100644 --- a/ports/atmel-samd/boards/stackrduino_m0_pro/mpconfigboard.mk +++ b/ports/atmel-samd/boards/stackrduino_m0_pro/mpconfigboard.mk @@ -7,12 +7,12 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" LONGINT_IMPL = MPZ CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 @@ -20,40 +20,5 @@ CIRCUITPY_MSGPACK = 0 CIRCUITPY_VECTORIO = 0 CIRCUITPY_BUSDEVICE = 0 -CFLAGS_INLINE_LIMIT = 55 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), ja) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif -ifeq ($(TRANSLATION), pl) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif -ifeq ($(TRANSLATION), fr) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif -ifeq ($(TRANSLATION), pt_BR) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -SUPEROPT_VM = 0 -endif -ifeq ($(TRANSLATION), es) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif diff --git a/ports/atmel-samd/boards/stackrduino_m0_pro/pins.c b/ports/atmel-samd/boards/stackrduino_m0_pro/pins.c index 95d2eb5a3d2d0..e0278aca0d35f 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/stringcar_m0_express/mpconfigboard.mk b/ports/atmel-samd/boards/stringcar_m0_express/mpconfigboard.mk index 68031e4a1840d..91644386f2011 100644 --- a/ports/atmel-samd/boards/stringcar_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/stringcar_m0_express/mpconfigboard.mk @@ -8,7 +8,6 @@ CHIP_VARIANT = SAMD21E18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = AT25SF161 LONGINT_IMPL = MPZ @@ -16,6 +15,7 @@ CIRCUITPY_BITBANG_APA102 = 1 CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_GAMEPAD = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_RTC = 0 diff --git a/ports/atmel-samd/boards/trellis_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/trellis_m4_express/mpconfigboard.mk index ee82b99c90c94..81df26b0c687b 100644 --- a/ports/atmel-samd/boards/trellis_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/trellis_m4_express/mpconfigboard.mk @@ -7,8 +7,7 @@ CHIP_VARIANT = SAMD51G19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "W25Q64JV_IQ, GD25Q64C" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, GD25Q64C" LONGINT_IMPL = MPZ # No I2S on SAMD51G diff --git a/ports/atmel-samd/boards/trinket_m0/mpconfigboard.mk b/ports/atmel-samd/boards/trinket_m0/mpconfigboard.mk index 735d4229730a4..fbbb974cdfc7d 100644 --- a/ports/atmel-samd/boards/trinket_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/trinket_m0/mpconfigboard.mk @@ -11,14 +11,7 @@ LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 SUPEROPT_GC = 0 - -CFLAGS_BOARD = --param max-inline-insns-auto=15 -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 -endif -ifeq ($(TRANSLATION), de_DE) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 35 SUPEROPT_VM = 0 -endif + +# On this particular board, these save about 180 bytes. On other boards, they may -increase- space used. +CFLAGS_BOARD = -fweb -frename-registers diff --git a/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk b/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk index 7eda151f36ac8..8c9dc71699d3f 100644 --- a/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk +++ b/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk @@ -7,12 +7,12 @@ CHIP_VARIANT = SAMD21E18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = W25Q32BV LONGINT_IMPL = MPZ CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_COUNTIO = 0 CIRCUITPY_RTC = 0 CIRCUITPY_FREQUENCYIO = 0 diff --git a/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk b/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk index 498429c9e8def..87619b5783d6a 100644 --- a/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk +++ b/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk @@ -7,6 +7,5 @@ CHIP_VARIANT = SAMD51J19A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q32JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" LONGINT_IMPL = MPZ diff --git a/ports/atmel-samd/boards/uchip/mpconfigboard.h b/ports/atmel-samd/boards/uchip/mpconfigboard.h index 5d6af4b782a78..6b8435877a84a 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/uchip/mpconfigboard.mk b/ports/atmel-samd/boards/uchip/mpconfigboard.mk index d08690a15aa7c..d6ba805b14413 100644 --- a/ports/atmel-samd/boards/uchip/mpconfigboard.mk +++ b/ports/atmel-samd/boards/uchip/mpconfigboard.mk @@ -10,7 +10,5 @@ INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = NONE CIRCUITPY_FULL_BUILD = 0 -# Always use aggressive inlining -CFLAGS_INLINE_LIMIT = 45 - SUPEROPT_GC = 0 +SUPEROPT_VM = 0 diff --git a/ports/atmel-samd/boards/ugame10/board.c b/ports/atmel-samd/boards/ugame10/board.c index 918fe2d59dd6f..f17b60ff60551 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/ugame10/mpconfigboard.mk b/ports/atmel-samd/boards/ugame10/mpconfigboard.mk index 640d421e8150e..74f438b714aeb 100644 --- a/ports/atmel-samd/boards/ugame10/mpconfigboard.mk +++ b/ports/atmel-samd/boards/ugame10/mpconfigboard.mk @@ -7,7 +7,6 @@ CHIP_VARIANT = SAMD21E18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = S25FL216K LONGINT_IMPL = NONE @@ -18,8 +17,10 @@ CIRCUITPY_ANALOGIO = 1 CIRCUITPY_GAMEPAD = 1 CIRCUITPY_DISPLAYIO = 1 +CIRCUITPY_PULSEIO = 0 CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_NEOPIXEL_WRITE = 0 @@ -34,10 +35,4 @@ FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-stage/ugame10 CIRCUITPY_DISPLAY_FONT = $(TOP)/ports/atmel-samd/boards/ugame10/brutalist-6.bdf -# Tweak inlining depending on language. -ifeq ($(TRANSLATION), zh_Latn_pinyin) -RELEASE_NEEDS_CLEAN_BUILD = 1 -CFLAGS_INLINE_LIMIT = 45 -else -CFLAGS_INLINE_LIMIT = 70 -endif +SUPEROPT_GC = 0 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 6baa43ffaa3cb..84960e73cf2cd 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 8d520f675b252..67882f6335f42 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/mpconfigboard.mk b/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.mk index ab2b861c03c69..1c96e1d235f6c 100644 --- a/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.mk +++ b/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.mk @@ -9,7 +9,6 @@ CHIP_VARIANT = SAMD21G18A CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 EXTERNAL_FLASH_DEVICES = "GD25Q16C, GD25Q64C" LONGINT_IMPL = MPZ @@ -17,6 +16,7 @@ CIRCUITPY_AUDIOIO = 1 # Disable modules that are unusable on this special-purpose board. CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_AUDIOBUSIO = 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 54ce173d81823..1a340ae226789 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/winterbloom_sol/mpconfigboard.mk b/ports/atmel-samd/boards/winterbloom_sol/mpconfigboard.mk index fcefaee9b8df3..81956a0b80f03 100644 --- a/ports/atmel-samd/boards/winterbloom_sol/mpconfigboard.mk +++ b/ports/atmel-samd/boards/winterbloom_sol/mpconfigboard.mk @@ -11,13 +11,13 @@ CHIP_VARIANT = SAMD51J20A CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "GD25Q64C, W25Q32JV_IQ" +EXTERNAL_FLASH_DEVICES = "GD25Q64C, W25Q32JVxQ" LONGINT_IMPL = MPZ # Disable modules that are unusable on this special-purpose board. CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_AUDIOIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_BLEIO_HCI = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 diff --git a/ports/atmel-samd/boards/xinabox_cc03/board.c b/ports/atmel-samd/boards/xinabox_cc03/board.c index 112b173eccb51..7af05ba45a53e 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 112b173eccb51..7af05ba45a53e 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 cfdfe75d8d7f0..40cd52134a43e 100644 --- a/ports/atmel-samd/common-hal/_pew/PewPew.c +++ b/ports/atmel-samd/common-hal/_pew/PewPew.c @@ -40,25 +40,27 @@ static uint8_t pewpew_tc_index = 0xff; +static volatile uint16_t pewpew_ticks = 0; 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; } pew_tick(); + ++pewpew_ticks; // Clear the interrupt bit. tc->COUNT16.INTFLAG.reg = TC_INTFLAG_MC0; } 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); @@ -95,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); @@ -123,3 +125,7 @@ void pew_reset(void) { } MP_STATE_VM(pew_singleton) = NULL; } + +uint16_t pew_get_ticks() { + return pewpew_ticks; +} diff --git a/ports/atmel-samd/common-hal/_pew/PewPew.h b/ports/atmel-samd/common-hal/_pew/PewPew.h index da1cae0a2cca9..523be01671add 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; @@ -44,5 +44,6 @@ typedef struct { void pew_init(void); void pewpew_interrupt_handler(uint8_t index); void pew_reset(void); +uint16_t pew_get_ticks(void); #endif // MICROPY_INCLUDED_PEW_PEWPEW_H diff --git a/ports/atmel-samd/common-hal/_pew/__init__.c b/ports/atmel-samd/common-hal/_pew/__init__.c index f3b23c606c036..b89b464dd336e 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 2bd218cddaaa7..262e44350c5ee 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 0b13ba7e14dc8..3a467f64dbebf 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 3ddd9cac667eb..f3b3310ebee04 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 0aa48c80472a5..2488b7b922e10 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 b/ports/atmel-samd/common-hal/audiobusio/PDMIn.c index 8911aef2f1aca..6ea70e39dcb05 100644 --- a/ports/atmel-samd/common-hal/audiobusio/PDMIn.c +++ b/ports/atmel-samd/common-hal/audiobusio/PDMIn.c @@ -367,11 +367,8 @@ static uint16_t filter_sample(uint32_t pdm_samples[4]) { // 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) { - uint8_t dma_channel = audio_dma_allocate_channel(); - uint8_t event_channel = find_sync_event_channel(); - if (event_channel >= EVSYS_SYNCH_NUM) { - mp_raise_RuntimeError(translate("All sync event channels in use")); - } + uint8_t dma_channel = dma_allocate_channel(); + uint8_t event_channel = find_sync_event_channel_raise(); // We allocate two buffers on the stack to use for double buffering. const uint8_t samples_per_buffer = SAMPLES_PER_BUFFER; @@ -476,7 +473,7 @@ uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* se } disable_event_channel(event_channel); - audio_dma_free_channel(dma_channel); + dma_free_channel(dma_channel); // Turn off serializer, but leave clock on, to avoid mic startup delay. i2s_set_serializer_enable(self->serializer, false); 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 0000000000000..e69de29bb2d1d diff --git a/ports/atmel-samd/common-hal/busio/I2C.c b/ports/atmel-samd/common-hal/busio/I2C.c index ffe74a2743be4..2551f7bf173e7 100644 --- a/ports/atmel-samd/common-hal/busio/I2C.c +++ b/ports/atmel-samd/common-hal/busio/I2C.c @@ -97,7 +97,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, if (!gpio_get_pin_level(sda->number) || !gpio_get_pin_level(scl->number)) { reset_pin_number(sda->number); reset_pin_number(scl->number); - mp_raise_RuntimeError(translate("SDA or SCL needs a pull up")); + mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); } #endif diff --git a/ports/atmel-samd/common-hal/displayio/ParallelBus.c b/ports/atmel-samd/common-hal/displayio/ParallelBus.c index f10dd2993bd1a..e5575f8dc2446 100644 --- a/ports/atmel-samd/common-hal/displayio/ParallelBus.c +++ b/ports/atmel-samd/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, uint32_t frequency) { uint8_t data_pin = data0->number; if (data_pin % 8 != 0) { @@ -55,7 +55,7 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* sel wrconfig |= 0xff << (data_pin % 32); } g->WRCONFIG.reg = wrconfig; - self->bus = ((uint8_t*) &g->OUT.reg) + (data0->number % 32 / 8); + self->bus = ((uint8_t *)&g->OUT.reg) + (data0->number % 32 / 8); self->command.base.type = &digitalio_digitalinout_type; common_hal_digitalio_digitalinout_construct(&self->command, command); @@ -95,7 +95,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); } @@ -108,7 +108,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; } @@ -124,17 +124,17 @@ 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; } 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.reg; - uint32_t* set_write = (uint32_t*) &self->write_group->OUTSET.reg; + uint32_t *clear_write = (uint32_t *)&self->write_group->OUTCLR.reg; + uint32_t *set_write = (uint32_t *)&self->write_group->OUTSET.reg; uint32_t mask = self->write_mask; for (uint32_t i = 0; i < data_length; i++) { *clear_write = mask; @@ -144,6 +144,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/atmel-samd/common-hal/i2cperipheral/I2CPeripheral.c b/ports/atmel-samd/common-hal/i2cperipheral/I2CPeripheral.c index 84642d4048ae3..53cbe854fd5c8 100644 --- a/ports/atmel-samd/common-hal/i2cperipheral/I2CPeripheral.c +++ b/ports/atmel-samd/common-hal/i2cperipheral/I2CPeripheral.c @@ -58,6 +58,10 @@ void common_hal_i2cperipheral_i2c_peripheral_construct(i2cperipheral_i2c_periphe samd_peripherals_sercom_clock_init(sercom, sercom_index); +#ifdef SAM_D5X_E5X + sercom->I2CS.CTRLC.bit.SDASETUP = 0x08; +#endif + sercom->I2CS.CTRLA.bit.SWRST = 1; while (sercom->I2CS.CTRLA.bit.SWRST || sercom->I2CS.SYNCBUSY.bit.SWRST) {} diff --git a/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c new file mode 100644 index 0000000000000..074c2b6d23234 --- /dev/null +++ b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c @@ -0,0 +1,198 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "py/runtime.h" + +#include "lib/utils/context_manager_helpers.h" +#include "lib/utils/interrupt_char.h" + +#include "shared-bindings/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "common-hal/imagecapture/ParallelImageCapture.h" + +#include "hal/include/hal_gpio.h" +#include "atmel_start_pins.h" + +#include "audio_dma.h" +#include "samd/clocks.h" +#include "samd/events.h" + +#define GPIO_PIN_FUNCTION_PCC (GPIO_PIN_FUNCTION_K) + +#define PIN_PCC_D0 (PIN_PA16) +#define PIN_PCC_DEN1 (PIN_PA12) +#define PIN_PCC_DEN2 (PIN_PA13) +#define PIN_PCC_CLK (PIN_PA14) + +void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data_clock, + const mcu_pin_obj_t *vertical_sync, + const mcu_pin_obj_t *horizontal_reference, + int data_count) +{ + if (data0->number != PIN_PCC_D0) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_data0); + } + // The peripheral supports 8, 10, 12, or 14 data bits, but the code only supports 8 at present + if (data_count != 8) + { + mp_raise_ValueError_varg(translate("Invalid data_count %d"), data_count); + } + if (vertical_sync && vertical_sync->number != PIN_PCC_DEN1) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_vsync); + } + if (horizontal_reference && horizontal_reference->number != PIN_PCC_DEN2) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_href); + } + if (data_clock->number != PIN_PCC_CLK) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_data_clock); + } + // technically, 0 was validated as free already but check again + for (int i=0; inumber + i)) { + mp_raise_ValueError_varg(translate("data pin #%d in use"), i); + } + } + + PCC->MR.bit.PCEN = 0; // Make sure PCC is disabled before setting MR reg + + PCC->IDR.reg = 0b1111; // Disable all PCC interrupts + MCLK->APBDMASK.bit.PCC_ = 1; // Enable PCC clock + + // Accumulate 4 bytes into RHR register (two 16-bit pixels) + PCC->MR.reg = PCC_MR_CID(0x1) | // Clear on falling DEN1 (VSYNC) + PCC_MR_ISIZE(0x0) | // Input data bus is 8 bits + PCC_MR_DSIZE(0x2); // "4 data" at a time (accumulate in RHR) + + PCC->MR.bit.PCEN = 1; // Enable PCC + + + // Now we know we can allocate all pins + self->data_count = data_count; + self->vertical_sync = vertical_sync ? vertical_sync->number : NO_PIN; + self->horizontal_reference = horizontal_reference ? horizontal_reference->number : NO_PIN; + gpio_set_pin_direction(PIN_PCC_CLK, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(PIN_PCC_CLK, GPIO_PULL_OFF); + gpio_set_pin_function(PIN_PCC_CLK, GPIO_PIN_FUNCTION_PCC); + //claim_pin_number(PIN_PCC_CLK); + if (vertical_sync) { + gpio_set_pin_direction(PIN_PCC_DEN1, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(PIN_PCC_DEN1, GPIO_PULL_OFF); + gpio_set_pin_function(PIN_PCC_DEN1, GPIO_PIN_FUNCTION_PCC); // VSYNC + //claim_pin_number(PIN_PCC_DEN1); + } + if (horizontal_reference) { + gpio_set_pin_direction(PIN_PCC_DEN2, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(PIN_PCC_DEN2, GPIO_PULL_OFF); + gpio_set_pin_function(PIN_PCC_DEN2, GPIO_PIN_FUNCTION_PCC); // HSYNC + //claim_pin_number(PIN_PCC_DEN2); + } + for (int i=0; ivertical_sync); + reset_pin_number(self->horizontal_reference); + reset_pin_number(PIN_PCC_CLK); + for (int i=0; idata_count; i++) { + reset_pin_number(PIN_PCC_D0 + i); + } + self->data_count = 0; +} + +bool common_hal_imagecapture_parallelimagecapture_deinited(imagecapture_parallelimagecapture_obj_t *self) +{ + return self->data_count == 0; +} + +static void setup_dma(DmacDescriptor* descriptor, size_t count, uint32_t *buffer) { + descriptor->BTCTRL.reg = DMAC_BTCTRL_VALID | + DMAC_BTCTRL_BLOCKACT_NOACT | + DMAC_BTCTRL_EVOSEL_BLOCK | + DMAC_BTCTRL_DSTINC | + DMAC_BTCTRL_BEATSIZE_WORD; + descriptor->BTCNT.reg = count; + descriptor->DSTADDR.reg = (uint32_t)buffer + 4*count; + descriptor->SRCADDR.reg = (uint32_t)&PCC->RHR.reg; + descriptor->DESCADDR.reg = 0; +} + +#include + +void common_hal_imagecapture_parallelimagecapture_capture(imagecapture_parallelimagecapture_obj_t *self, void *buffer, size_t bufsize) +{ + + uint8_t dma_channel = dma_allocate_channel(); + + uint32_t *dest = buffer; + size_t count = bufsize / 4; // PCC receives 4 bytes (2 pixels) at a time + + turn_on_event_system(); + + setup_dma(dma_descriptor(dma_channel), count, dest); + dma_configure(dma_channel, PCC_DMAC_ID_RX, true); + + if (self->vertical_sync) { + const volatile uint32_t *vsync_reg = &PORT->Group[(self->vertical_sync / 32)].IN.reg; + uint32_t vsync_bit = 1 << (self->vertical_sync % 32); + + while (*vsync_reg & vsync_bit) + { + // Wait for VSYNC low (frame end) + + RUN_BACKGROUND_TASKS; + // Allow user to break out of a timeout with a KeyboardInterrupt. + if (mp_hal_is_interrupted()) { + dma_free_channel(dma_channel); + return; + } + } + } + + dma_enable_channel(dma_channel); + + while (DMAC->Channel[dma_channel].CHCTRLA.bit.ENABLE) { + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + break; + } + } + + dma_disable_channel(dma_channel); + dma_free_channel(dma_channel); +} diff --git a/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.h b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.h new file mode 100644 index 0000000000000..67311c5b00727 --- /dev/null +++ b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.h @@ -0,0 +1,34 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +#include "shared-bindings/imagecapture/ParallelImageCapture.h" + +struct imagecapture_parallelimagecapture_obj { + mp_obj_base_t base; + uint8_t data_pin, data_clock, vertical_sync, horizontal_reference, data_count; +}; diff --git a/ports/atmel-samd/common-hal/imagecapture/__init__.c b/ports/atmel-samd/common-hal/imagecapture/__init__.c new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/atmel-samd/common-hal/imagecapture/__init__.h b/ports/atmel-samd/common-hal/imagecapture/__init__.h new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/atmel-samd/common-hal/pulseio/PulseIn.c b/ports/atmel-samd/common-hal/pulseio/PulseIn.c index f65d583640b1e..20c79642a3038 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseIn.c +++ b/ports/atmel-samd/common-hal/pulseio/PulseIn.c @@ -137,7 +137,7 @@ void pulsein_interrupt_handler(uint8_t channel) { void pulsein_reset() { #ifdef SAMD21 - rtc_end_pulsein(); + rtc_end_pulse(); #endif refcount = 0; pulsein_tc_index = 0xff; @@ -236,7 +236,7 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, // Set config will enable the EIC. pulsein_set_config(self, true); #ifdef SAMD21 - rtc_start_pulsein(); + rtc_start_pulse(); #endif } @@ -250,7 +250,7 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { return; } #ifdef SAMD21 - rtc_end_pulsein(); + rtc_end_pulse(); #endif set_eic_handler(self->channel, EIC_HANDLER_NO_INTERRUPT); turn_off_eic_channel(self->channel); diff --git a/ports/atmel-samd/common-hal/pulseio/PulseIn.h b/ports/atmel-samd/common-hal/pulseio/PulseIn.h index b91bbd703bb3b..e8fed8e5a03e3 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseIn.h +++ b/ports/atmel-samd/common-hal/pulseio/PulseIn.h @@ -51,8 +51,8 @@ void pulsein_reset(void); void pulsein_interrupt_handler(uint8_t channel); void pulsein_timer_interrupt_handler(uint8_t index); #ifdef SAMD21 -void rtc_start_pulsein(void); -void rtc_end_pulsein(void); +void rtc_start_pulse(void); +void rtc_end_pulse(void); #endif diff --git a/ports/atmel-samd/common-hal/pulseio/PulseOut.c b/ports/atmel-samd/common-hal/pulseio/PulseOut.c index 086052a973c82..ebfd4e7b1a3e8 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseOut.c +++ b/ports/atmel-samd/common-hal/pulseio/PulseOut.c @@ -93,6 +93,9 @@ void pulseout_reset() { refcount = 0; pulseout_tc_index = 0xff; active_pincfg = NULL; +#ifdef SAMD21 + rtc_end_pulse(); +#endif } void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, @@ -159,6 +162,10 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, // Turn off the pinmux which should connect the port output. turn_off(self->pincfg); +#ifdef SAMD21 + rtc_start_pulse(); +#endif + } bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self) { @@ -180,6 +187,9 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { pulseout_tc_index = 0xff; } self->pin = NO_PIN; +#ifdef SAMD21 + rtc_end_pulse(); +#endif } void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pulses, uint16_t length) { diff --git a/ports/atmel-samd/common-hal/pulseio/PulseOut.h b/ports/atmel-samd/common-hal/pulseio/PulseOut.h index 634088128fb42..8f8e504fab220 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseOut.h +++ b/ports/atmel-samd/common-hal/pulseio/PulseOut.h @@ -39,5 +39,9 @@ typedef struct { void pulseout_reset(void); void pulseout_interrupt_handler(uint8_t index); +#ifdef SAMD21 +void rtc_start_pulse(void); +void rtc_end_pulse(void); +#endif #endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEOUT_H diff --git a/ports/atmel-samd/common-hal/pwmio/PWMOut.c b/ports/atmel-samd/common-hal/pwmio/PWMOut.c index b5142c21e1692..c46145d7d73b1 100644 --- a/ports/atmel-samd/common-hal/pwmio/PWMOut.c +++ b/ports/atmel-samd/common-hal/pwmio/PWMOut.c @@ -156,7 +156,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, return PWMOUT_INVALID_PIN; } - if (frequency == 0 || frequency > 6000000) { + uint32_t system_clock = common_hal_mcu_processor_get_frequency(); + if (frequency == 0 || frequency > system_clock/2) { return PWMOUT_INVALID_FREQUENCY; } @@ -237,7 +238,6 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, resolution = tcc_sizes[timer->index]; } // First determine the divisor that gets us the highest resolution. - uint32_t system_clock = common_hal_mcu_processor_get_frequency(); uint32_t top; uint8_t divisor; for (divisor = 0; divisor < 8; divisor++) { @@ -413,7 +413,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) { - if (frequency == 0 || frequency > 6000000) { + uint32_t system_clock = common_hal_mcu_processor_get_frequency(); + if (frequency == 0 || frequency > system_clock/2) { mp_raise_ValueError(translate("Invalid PWM frequency")); } const pin_timer_t* t = self->timer; @@ -424,7 +425,6 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, // TCC resolution varies so look it up. resolution = tcc_sizes[t->index]; } - uint32_t system_clock = common_hal_mcu_processor_get_frequency(); uint32_t new_top; uint8_t new_divisor; for (new_divisor = 0; new_divisor < 8; new_divisor++) { diff --git a/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c b/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c index 55b0c2f12544b..6daf20aeaa0b8 100644 --- a/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c @@ -31,7 +31,7 @@ #include "samd/timers.h" #include "timer_handler.h" -void *common_hal_rgbmatrix_timer_allocate() { +void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self) { uint8_t timer_index = find_free_timer(); if (timer_index == 0xff) { return NULL; diff --git a/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.h b/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.h index 48de4dcb212db..2378cf173567a 100644 --- a/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.h +++ b/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.h @@ -27,7 +27,9 @@ #ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_RGBMATRIX_RGBMATRIX_H #define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_RGBMATRIX_RGBMATRIX_H -void *common_hal_rgbmatrix_timer_allocate(void); +#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*); diff --git a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c index 0922718f9624c..4b74b438ff3ca 100644 --- a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c @@ -25,6 +25,7 @@ */ #include "common-hal/rotaryio/IncrementalEncoder.h" +#include "shared-module/rotaryio/IncrementalEncoder.h" #include "atmel_start_pins.h" @@ -68,11 +69,9 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode self->position = 0; self->quarter_count = 0; - // Top two bits of self->last_state don't matter, because they'll be gone as soon as - // interrupt handler is called. - self->last_state = + shared_module_softencoder_state_init(self, ((uint8_t) gpio_get_pin_level(self->pin_a) << 1) | - (uint8_t) gpio_get_pin_level(self->pin_b); + (uint8_t) gpio_get_pin_level(self->pin_b)); claim_pin(pin_a); claim_pin(pin_b); @@ -106,66 +105,12 @@ 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) { - return self->position; -} - -void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t* self, - mp_int_t new_position) { - self->position = new_position; -} - void incrementalencoder_interrupt_handler(uint8_t channel) { rotaryio_incrementalencoder_obj_t* self = get_eic_channel_data(channel); - // This table also works for detent both at 11 and 00 - // For 11 at detent: - // Turning cw: 11->01->00->10->11 - // Turning ccw: 11->10->00->01->11 - // For 00 at detent: - // Turning cw: 00->10->11->10->00 - // Turning ccw: 00->01->11->10->00 - - // index table by state - #define BAD 7 - static const int8_t transitions[16] = { - 0, // 00 -> 00 no movement - -1, // 00 -> 01 3/4 ccw (11 detent) or 1/4 ccw (00 at detent) - +1, // 00 -> 10 3/4 cw or 1/4 cw - BAD, // 00 -> 11 non-Gray-code transition - +1, // 01 -> 00 2/4 or 4/4 cw - 0, // 01 -> 01 no movement - BAD, // 01 -> 10 non-Gray-code transition - -1, // 01 -> 11 4/4 or 2/4 ccw - -1, // 10 -> 00 2/4 or 4/4 ccw - BAD, // 10 -> 01 non-Gray-code transition - 0, // 10 -> 10 no movement - +1, // 10 -> 11 4/4 or 2/4 cw - BAD, // 11 -> 00 non-Gray-code transition - +1, // 11 -> 01 1/4 or 3/4 cw - -1, // 11 -> 10 1/4 or 3/4 ccw - 0, // 11 -> 11 no movement - }; - - // Shift the old AB bits to the "old" position, and set the new AB bits. - // TODO(tannewt): If we need more speed then read the pin directly. gpio_get_pin_level has - // smarts to compensate for pin direction we don't need. - self->last_state = (self->last_state & 0x3) << 2 | + uint8_t new_state = ((uint8_t) gpio_get_pin_level(self->pin_a) << 1) | (uint8_t) gpio_get_pin_level(self->pin_b); - int8_t quarter_incr = transitions[self->last_state]; - if (quarter_incr == BAD) { - // Missed a transition. We don't know which way we're going, so do nothing. - return; - } - - self->quarter_count += quarter_incr; - if (self->quarter_count >= 4) { - self->position += 1; - self->quarter_count = 0; - } else if (self->quarter_count <= -4) { - self->position -= 1; - self->quarter_count = 0; - } + shared_module_softencoder_state_update(self, new_state); } diff --git a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h index e07cc84d5daef..2560997a97448 100644 --- a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h +++ b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.h @@ -35,10 +35,10 @@ typedef struct { mp_obj_base_t base; uint8_t pin_a; uint8_t pin_b; - uint8_t eic_channel_a:4; - uint8_t eic_channel_b:4; - uint8_t last_state:4; // - int8_t quarter_count:4; // count intermediate transitions between detents + uint8_t eic_channel_a; + uint8_t eic_channel_b; + uint8_t state; // + int8_t quarter_count; // count intermediate transitions between detents mp_int_t position; } rotaryio_incrementalencoder_obj_t; diff --git a/ports/atmel-samd/common-hal/supervisor/Runtime.c b/ports/atmel-samd/common-hal/supervisor/Runtime.c index 6be38f216ac16..974f26cec1684 100755 --- a/ports/atmel-samd/common-hal/supervisor/Runtime.c +++ b/ports/atmel-samd/common-hal/supervisor/Runtime.c @@ -28,10 +28,10 @@ #include "shared-bindings/supervisor/Runtime.h" #include "supervisor/serial.h" -bool common_hal_get_serial_connected(void) { +bool common_hal_supervisor_runtime_get_serial_connected(void) { return (bool) serial_connected(); } -bool common_hal_get_serial_bytes_available(void) { +bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { return (bool) serial_bytes_available(); } diff --git a/ports/atmel-samd/eic_handler.c b/ports/atmel-samd/eic_handler.c index 7f26bdefbfdbc..226dafc76585f 100644 --- a/ports/atmel-samd/eic_handler.c +++ b/ports/atmel-samd/eic_handler.c @@ -29,7 +29,7 @@ #include "common-hal/rotaryio/IncrementalEncoder.h" #include "common-hal/countio/Counter.h" #include "shared-bindings/microcontroller/__init__.h" -//#include "samd/external_interrupts.h" +// #include "samd/external_interrupts.h" #include "eic_handler.h" // Which handler should be called for a particular channel? @@ -42,31 +42,31 @@ void set_eic_handler(uint8_t channel, uint8_t eic_handler) { void shared_eic_handler(uint8_t channel) { uint8_t handler = eic_channel_handler[channel]; switch (handler) { -#if CIRCUITPY_PULSEIO - case EIC_HANDLER_PULSEIN: - pulsein_interrupt_handler(channel); - break; -#endif + #if CIRCUITPY_PULSEIO + case EIC_HANDLER_PULSEIN: + pulsein_interrupt_handler(channel); + break; + #endif -#if CIRCUITPY_PS2IO - case EIC_HANDLER_PS2: - ps2_interrupt_handler(channel); - break; -#endif + #if CIRCUITPY_PS2IO + case EIC_HANDLER_PS2: + ps2_interrupt_handler(channel); + break; + #endif -#if CIRCUITPY_ROTARYIO - case EIC_HANDLER_INCREMENTAL_ENCODER: - incrementalencoder_interrupt_handler(channel); - break; -#endif + #if CIRCUITPY_ROTARYIO + case EIC_HANDLER_INCREMENTAL_ENCODER: + incrementalencoder_interrupt_handler(channel); + break; + #endif -#if CIRCUITPY_COUNTIO - case EIC_HANDLER_COUNTER: - counter_interrupt_handler(channel); - break; -#endif + #if CIRCUITPY_COUNTIO + case EIC_HANDLER_COUNTER: + counter_interrupt_handler(channel); + break; + #endif - default: - break; + default: + break; } } diff --git a/ports/atmel-samd/fatfs_port.c b/ports/atmel-samd/fatfs_port.c index c65a73a428fcc..e6eee2049511d 100644 --- a/ports/atmel-samd/fatfs_port.c +++ b/ports/atmel-samd/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/atmel-samd/ld_defines.c b/ports/atmel-samd/ld_defines.c index 18f49d42c6916..56e26d8dca38e 100644 --- a/ports/atmel-samd/ld_defines.c +++ b/ports/atmel-samd/ld_defines.c @@ -9,22 +9,22 @@ // The next line is a marker to start looking for definitions. Lines above the next line are ignored. // START_LD_DEFINES -/*RAM_SIZE=*/ RAM_SIZE; -/*FLASH_SIZE=*/ FLASH_SIZE; +/*RAM_SIZE=*/ RAM_SIZE; +/*FLASH_SIZE=*/ FLASH_SIZE; -/*BOOTLOADER_SIZE=*/ BOOTLOADER_SIZE; -/*BOOTLOADER_START_ADDR=*/ BOOTLOADER_START_ADDR; +/*BOOTLOADER_SIZE=*/ BOOTLOADER_SIZE; +/*BOOTLOADER_START_ADDR=*/ BOOTLOADER_START_ADDR; -/*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_INTERNAL_CONFIG_START_ADDR=*/ CIRCUITPY_INTERNAL_CONFIG_START_ADDR; -/*CIRCUITPY_INTERNAL_CONFIG_SIZE=*/ CIRCUITPY_INTERNAL_CONFIG_SIZE; +/*CIRCUITPY_INTERNAL_CONFIG_START_ADDR=*/ CIRCUITPY_INTERNAL_CONFIG_START_ADDR; +/*CIRCUITPY_INTERNAL_CONFIG_SIZE=*/ CIRCUITPY_INTERNAL_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; diff --git a/ports/atmel-samd/modules/frozentest.py b/ports/atmel-samd/modules/frozentest.py index 0f99b74297fbb..78cdd60bf0431 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/mpconfigport.h b/ports/atmel-samd/mpconfigport.h index d2a529485e6a4..c66ab99ab2a4d 100644 --- a/ports/atmel-samd/mpconfigport.h +++ b/ports/atmel-samd/mpconfigport.h @@ -38,7 +38,7 @@ // HMCRAMC0_SIZE is defined in the ASF4 include files for each SAMD21 chip. #define RAM_SIZE HMCRAMC0_SIZE -#define BOOTLOADER_SIZE (8*1024) +#define BOOTLOADER_SIZE (8 * 1024) #define CIRCUITPY_MCU_FAMILY samd21 #define MICROPY_PY_SYS_PLATFORM "Atmel SAMD21" #define SPI_FLASH_MAX_BAUDRATE 8000000 @@ -67,7 +67,7 @@ // HSRAM_SIZE is defined in the ASF4 include files for each SAM_D5X_E5X chip. #define RAM_SIZE HSRAM_SIZE -#define BOOTLOADER_SIZE (16*1024) +#define BOOTLOADER_SIZE (16 * 1024) #define CIRCUITPY_MCU_FAMILY samd51 #ifdef SAMD51 #define MICROPY_PY_SYS_PLATFORM "MicroChip SAMD51" @@ -96,7 +96,7 @@ #ifdef SAMD21 #if INTERNAL_FLASH_FILESYSTEM -#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (64*1024) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (64 * 1024) #else #define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (0) #endif @@ -131,7 +131,7 @@ #endif #ifndef CIRCUITPY_DEFAULT_STACK_SIZE -#define CIRCUITPY_DEFAULT_STACK_SIZE (24*1024) +#define CIRCUITPY_DEFAULT_STACK_SIZE (24 * 1024) #endif #ifndef SAMD5x_E5x_BOD33_LEVEL @@ -148,7 +148,7 @@ // If CIRCUITPY is internal, use half of flash for it. #if INTERNAL_FLASH_FILESYSTEM #ifndef CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE - #define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (FLASH_SIZE/2) + #define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (FLASH_SIZE / 2) #endif #else #define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (0) diff --git a/ports/atmel-samd/mpconfigport.mk b/ports/atmel-samd/mpconfigport.mk index fb9cdf2e66c67..f04055d43be21 100644 --- a/ports/atmel-samd/mpconfigport.mk +++ b/ports/atmel-samd/mpconfigport.mk @@ -18,7 +18,18 @@ ifeq ($(LONGINT_IMPL),LONGLONG) MPY_TOOL_LONGINT_IMPL = -mlongint-impl=longlong endif +INTERNAL_LIBM = 1 + +USB_SERIAL_NUMBER_LENGTH = 32 + +# Number of USB endpoint pairs. +USB_NUM_EP = 8 + +CIRCUITPY_ROTARYIO_SOFTENCODER = 1 + +###################################################################### # Put samd21-only choices here. + ifeq ($(CHIP_FAMILY),samd21) # The ?='s allow overriding in mpconfigboard.mk. @@ -27,8 +38,10 @@ CIRCUITPY_AUDIOMIXER ?= 0 CIRCUITPY_BINASCII ?= 0 CIRCUITPY_AUDIOMP3 ?= 0 CIRCUITPY_BUILTINS_POW3 ?= 0 +CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE ?= 1 CIRCUITPY_FREQUENCYIO ?= 0 CIRCUITPY_JSON ?= 0 +CIRCUITPY_SYNTHIO ?= 0 CIRCUITPY_TOUCHIO_USE_NATIVE ?= 1 # No room for HCI _bleio on SAMD21. @@ -39,8 +52,8 @@ CIRCUITPY_SDCARDIO ?= 0 # Not enough RAM for framebuffers CIRCUITPY_FRAMEBUFFERIO ?= 0 -# SAMD21 needs separate endpoint pairs for MSC BULK IN and BULK OUT, otherwise it's erratic. -USB_MSC_EP_NUM_OUT = 1 +# Not enough room in 192kB or 256kB builds for secondary CDC. +CIRCUITPY_USB_CDC ?= 0 CIRCUITPY_ULAB = 0 @@ -55,9 +68,13 @@ CIRCUITPY_TERMINALIO = 0 endif endif # samd21 +###################################################################### +###################################################################### # Put samd51-only choices here. + ifeq ($(CHIP_FAMILY),samd51) + # No native touchio on SAMD51. CIRCUITPY_TOUCHIO_USE_NATIVE = 0 @@ -70,9 +87,23 @@ CIRCUITPY_RGBMATRIX ?= $(CIRCUITPY_FULL_BUILD) CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_FULL_BUILD) endif # samd51 +###################################################################### -INTERNAL_LIBM = 1 +###################################################################### +# Put same51-only choices here. -USB_SERIAL_NUMBER_LENGTH = 32 +ifeq ($(CHIP_FAMILY),same51) -USB_NUM_EP = 8 +# No native touchio on SAMD51. +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + +# The ?='s allow overriding in mpconfigboard.mk. + +CIRCUITPY_NETWORK ?= 0 +CIRCUITPY_PS2IO ?= 1 +CIRCUITPY_SAMD ?= 1 +CIRCUITPY_RGBMATRIX ?= $(CIRCUITPY_FULL_BUILD) +CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_FULL_BUILD) + +endif # same51 +###################################################################### diff --git a/ports/atmel-samd/mphalport.c b/ports/atmel-samd/mphalport.c index b497b89cd8b8d..5ebce1a85786c 100644 --- a/ports/atmel-samd/mphalport.c +++ b/ports/atmel-samd/mphalport.c @@ -56,15 +56,15 @@ extern uint32_t common_hal_mcu_processor_get_frequency(void); // Testing done at 48 MHz on SAMD21 and 120 MHz on SAMD51, multiplication and division cancel out. // But get the frequency just in case. #ifdef SAMD21 -#define DELAY_LOOP_ITERATIONS_PER_US ( (10U*48000000U) / common_hal_mcu_processor_get_frequency()) +#define DELAY_LOOP_ITERATIONS_PER_US ((10U * 48000000U) / common_hal_mcu_processor_get_frequency()) #endif #ifdef SAM_D5X_E5X -#define DELAY_LOOP_ITERATIONS_PER_US ( (30U*120000000U) / common_hal_mcu_processor_get_frequency()) +#define DELAY_LOOP_ITERATIONS_PER_US ((30U * 120000000U) / common_hal_mcu_processor_get_frequency()) #endif void mp_hal_delay_us(mp_uint_t delay) { - for (uint32_t i = delay*DELAY_LOOP_ITERATIONS_PER_US; i > 0; i--) { - asm volatile("nop"); + for (uint32_t i = delay * DELAY_LOOP_ITERATIONS_PER_US; i > 0; i--) { + asm volatile ("nop"); } } diff --git a/ports/atmel-samd/mphalport.h b/ports/atmel-samd/mphalport.h index adc65ade530a7..8b9b7fd14c532 100644 --- a/ports/atmel-samd/mphalport.h +++ b/ports/atmel-samd/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/atmel-samd/supervisor/port.c b/ports/atmel-samd/supervisor/port.c index c2e27e1e7ffdd..2137c47559fc8 100644 --- a/ports/atmel-samd/supervisor/port.c +++ b/ports/atmel-samd/supervisor/port.c @@ -102,12 +102,12 @@ static void rtc_set_continuous(bool continuous) { while (RTC->MODE0.STATUS.bit.SYNCBUSY); } -void rtc_start_pulsein(void) { +void rtc_start_pulse(void) { rtc_set_continuous(true); hold_interrupt = true; } -void rtc_end_pulsein(void) { +void rtc_end_pulse(void) { hold_interrupt = false; rtc_set_continuous(false); } diff --git a/ports/atmel-samd/timer_handler.c b/ports/atmel-samd/timer_handler.c index 16d65334e09c9..eab9311d6a826 100644 --- a/ports/atmel-samd/timer_handler.c +++ b/ports/atmel-samd/timer_handler.c @@ -49,31 +49,31 @@ void shared_timer_handler(bool is_tc, uint8_t index) { // Make sure to add the handler #define to timer_handler.h if (is_tc) { uint8_t handler = tc_handler[index]; - switch(handler) { + switch (handler) { case TC_HANDLER_PULSEIN: - #if CIRCUITPY_PULSEIO + #if CIRCUITPY_PULSEIO pulsein_timer_interrupt_handler(index); - #endif + #endif break; case TC_HANDLER_PULSEOUT: - #if CIRCUITPY_PULSEIO + #if CIRCUITPY_PULSEIO pulseout_interrupt_handler(index); - #endif + #endif break; case TC_HANDLER_PEW: - #if CIRCUITPY_PEW + #if CIRCUITPY_PEW pewpew_interrupt_handler(index); - #endif + #endif break; case TC_HANDLER_FREQUENCYIN: - #if CIRCUITPY_FREQUENCYIO + #if CIRCUITPY_FREQUENCYIO frequencyin_interrupt_handler(index); - #endif + #endif break; case TC_HANDLER_RGBMATRIX: - #if CIRCUITPY_RGBMATRIX + #if CIRCUITPY_RGBMATRIX _PM_IRQ_HANDLER(); - #endif + #endif break; default: break; diff --git a/ports/atmel-samd/tools/gen_pin_name_table.py b/ports/atmel-samd/tools/gen_pin_name_table.py index 4e25c39fd92aa..a78144d400424 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 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 @@ # 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 @@ 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 9668d2208a4e5..d505c81bdc49d 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 @@ def defines(name, suffix): #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 48c4a085f551f..bfdcd696c26a1 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 @@ def defines(name, function): #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 7b7bac10fe6b4..a747d6b061a92 100644 --- a/ports/atmel-samd/tools/update_asf.py +++ b/ports/atmel-samd/tools/update_asf.py @@ -11,7 +11,11 @@ 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 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/Makefile b/ports/cxd56/Makefile index 1c48a23ca527c..15eb5e64c71b9 100644 --- a/ports/cxd56/Makefile +++ b/ports/cxd56/Makefile @@ -151,7 +151,7 @@ LDFLAGS = \ --end-group \ -L$(BUILD) \ -CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_CXD56 -DCFG_TUD_MIDI_RX_BUFSIZE=512 -DCFG_TUD_CDC_RX_BUFSIZE=512 -DCFG_TUD_MIDI_TX_BUFSIZE=512 -DCFG_TUD_CDC_TX_BUFSIZE=512 -DCFG_TUD_MSC_BUFSIZE=512 $(CFLAGS_MOD) +CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_CXD56 -DCFG_TUD_MIDI_RX_BUFSIZE=512 -DCFG_TUD_CDC_RX_BUFSIZE=1024 -DCFG_TUD_MIDI_TX_BUFSIZE=512 -DCFG_TUD_CDC_TX_BUFSIZE=1024 -DCFG_TUD_MSC_BUFSIZE=512 $(CFLAGS_MOD) SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ diff --git a/ports/cxd56/background.c b/ports/cxd56/background.c index 6de6d7275b5c4..644a5d7b0beff 100644 --- a/ports/cxd56/background.c +++ b/ports/cxd56/background.c @@ -30,6 +30,9 @@ #include "supervisor/filesystem.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/cxd56/boards/spresense/board.c b/ports/cxd56/boards/spresense/board.c index fd27d3493a920..7d6297b648938 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/boards/spresense/mpconfigboard.mk b/ports/cxd56/boards/spresense/mpconfigboard.mk index 80c6e4b6924de..966fa023f0018 100644 --- a/ports/cxd56/boards/spresense/mpconfigboard.mk +++ b/ports/cxd56/boards/spresense/mpconfigboard.mk @@ -4,5 +4,5 @@ USB_PRODUCT = "Spresense" USB_MANUFACTURER = "Sony" INTERNAL_FLASH_FILESYSTEM = 1 - +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_MSGPACK = 0 diff --git a/ports/cxd56/common-hal/analogio/AnalogIn.c b/ports/cxd56/common-hal/analogio/AnalogIn.c index cdf37c06a7d1e..d1bd68cfbe90a 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; @@ -105,20 +105,27 @@ bool common_hal_analogio_analogin_deinited(analogio_analogin_obj_t *self) { } uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { - uint16_t value = 0; + int16_t value = 0; read(analogin_dev[self->number].fd, &value, sizeof(value)); - return value; + return (uint16_t)32768 + (uint16_t)value; } // Reference voltage is a fixed value which is depending on the board. // e.g.) -// - Reference Voltage of A4 and A5 pins on Main Board is 0.7V. -// - Reference Voltage of A0 ~ A5 pins on External Interface board -// is selected 3.3V or 5.0V by a IO Volt jumper pin. +// - Reference Voltage of A2 and A3 pins on Main Board is 0.7V. +// - Reference Voltage of A0 ~ A5 pins on External Interface board is 5.0V float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t *self) { - return 0.0f; + float voltage; + + if (self->number == 2 || self->number == 3) { + voltage = 0.0f; + } else { + voltage = 5.0f; + } + + return voltage; } void analogin_reset(void) { diff --git a/ports/cxd56/common-hal/busio/I2C.c b/ports/cxd56/common-hal/busio/I2C.c index 127b6e75cd592..7b9420fa1b7d8 100644 --- a/ports/cxd56/common-hal/busio/I2C.c +++ b/ports/cxd56/common-hal/busio/I2C.c @@ -27,6 +27,7 @@ #include #include #include +#include #include "py/runtime.h" @@ -49,6 +50,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, const mcu_pin_obj_t * self->sda_pin = sda; self->frequency = frequency; self->i2c_dev = cxd56_i2cbus_initialize(0); + CXD56_PIN_CONFIGS(PINCONFS_I2C0); } void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { @@ -101,9 +103,9 @@ 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); + return -I2C_TRANSFER(self->i2c_dev, &msg, 1); } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t address, uint8_t *data, size_t len) { @@ -114,7 +116,7 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t address, uint8 msg.flags = I2C_M_READ; msg.buffer = data; msg.length = len; - return I2C_TRANSFER(self->i2c_dev, &msg, 1); + return -I2C_TRANSFER(self->i2c_dev, &msg, 1); } void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { diff --git a/ports/cxd56/common-hal/busio/I2C.h b/ports/cxd56/common-hal/busio/I2C.h index cdef270bfa513..4d1d3ce9b8635 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 2d365d4826459..ff834f7f38292 100644 --- a/ports/cxd56/common-hal/busio/SPI.c +++ b/ports/cxd56/common-hal/busio/SPI.c @@ -26,6 +26,7 @@ #include #include +#include #include "py/runtime.h" @@ -35,10 +36,16 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t * const mcu_pin_obj_t *mosi, const mcu_pin_obj_t *miso) { int port = -1; - if (clock->number == PIN_SPI4_SCK && mosi->number == PIN_SPI4_MOSI && miso->number == PIN_SPI4_MISO) { + if (clock->number == PIN_SPI4_SCK && + (mosi == NULL || mosi->number == PIN_SPI4_MOSI) && + (miso == NULL || miso->number == PIN_SPI4_MISO)) { port = 4; - } else if (clock->number == PIN_EMMC_CLK && mosi->number == PIN_EMMC_DATA0 && miso->number == PIN_EMMC_DATA1) { + CXD56_PIN_CONFIGS(PINCONFS_SPI4); + } else if (clock->number == PIN_EMMC_CLK && + (mosi == NULL || mosi->number == PIN_EMMC_DATA0) && + (miso == NULL || miso->number == PIN_EMMC_DATA1)) { port = 5; + CXD56_PIN_CONFIGS(PINCONFS_EMMCA_SPI5); } if (port < 0) { @@ -140,7 +147,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 8985a60d9f460..ee04de08c4e12 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 52d2afc0c2210..91fbe52441458 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,12 +53,15 @@ 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) { + int i; + int count; + char tmp; struct termios tio; if ((rts != NULL) || (cts != NULL) || (rs485_dir != NULL) || (rs485_invert)) { @@ -96,6 +99,14 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, if (busio_uart_dev[self->number].fd < 0) { mp_raise_ValueError(translate("Could not initialize UART")); } + + // Wait to make sure the UART is ready + usleep(1000); + // Clear RX FIFO + ioctl(busio_uart_dev[self->number].fd, FIONREAD, (long unsigned int)&count); + for (i = 0; i < count; i++) { + read(busio_uart_dev[self->number].fd, &tmp, 1); + } } ioctl(busio_uart_dev[self->number].fd, TCGETS, (long unsigned int)&tio); @@ -180,7 +191,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 35e2ab88229cc..5e159d61dcb59 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 c0aaa3cfbd552..f345f5261d1a2 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 6759a2dcab672..259fc57162927 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 3cb187de61cef..b5efe37ce6536 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 7aa3b839d7801..499e0e5f0482c 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 d4b0e23becc2e..e44d293f0006d 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 7c3e4a9d05dc5..0d2fbbfd968a4 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 f08e7cd7a0bd9..be0d51f575a37 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 e0eb7abde81fb..61806540b13f4 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 cf7de422c1251..cf8986a4f8da1 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 cbdcd47069972..04f6ccdba2e5f 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 a0d9e70ab17fa..6ecdc2581eb0b --- a/ports/cxd56/common-hal/supervisor/Runtime.c +++ b/ports/cxd56/common-hal/supervisor/Runtime.c @@ -27,10 +27,10 @@ #include "shared-bindings/supervisor/Runtime.h" #include "supervisor/serial.h" -bool common_hal_get_serial_connected(void) { - return (bool) serial_connected(); +bool common_hal_supervisor_runtime_get_serial_connected(void) { + return (bool)serial_connected(); } -bool common_hal_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); +bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { + return (bool)serial_bytes_available(); } diff --git a/ports/cxd56/fatfs_port.c b/ports/cxd56/fatfs_port.c index e986b4c6eb5c9..a58465b98316c 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 02a175505da67..e946ee5348a5a 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]; - - 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); + 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 + 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]; - - 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); + 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 + 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]; - - 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); + 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 */ + + 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]; - - 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); - - bytecpy(lk, 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[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); } -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; - - /* updating T */ - - if (t[1] & 0x01u) - { - t[0] ^= 0xa8u; - t[1] ^= 0x30u; +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; + + /* updating T */ + + 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 */ - }; +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; + unsigned char lk[16]; + unsigned char con128[4 * 60]; + int i; - /* generating CONi^(128) (0 <= i < 60, lk = 30) */ + /* generating CONi^(128) (0 <= i < 60, lk = 30) */ - clefiaconset(con128, iv, 30); + clefiaconset(con128, iv, 30); - /* GFN_{4,12} (generating L from K) */ + /* GFN_{4,12} (generating L from K) */ - clefiagfn4(lk, skey, con128, 12); + clefiagfn4(lk, skey, con128, 12); - bytecpy(rk, skey, 8); /* initial whitening key (WK0, WK1) */ - rk += 8; - for (i = 0; i < 9; i++) + bytecpy(rk, skey, 8); /* initial whitening key (WK0, WK1) */ + rk += 8; + for (i = 0; i < 9; i++) { - /* round key (RKi (0 <= i < 36)) */ + /* 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 */ + 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 a0e02587da98b..0d67643710793 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 94a9c81ba3cd2..e19ce210a66b6 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 c447ad7dab1ff..23bafb834780d 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 'h': - default: - show_help = 1; + 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; } } - 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; - - fp = fopen(filename, "rb"); - if (!fp) - { - return NULL; +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; } - 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; - - snlen = alignup(strlen(savename) + 1, 16); - - nphs = 0; - psize = 0; - for (i = 0, ph = elf->phdr; i < elf->ehdr->e_phnum; i++, ph++) + 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); + + 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]; - - args = parse_args(argc, argv); - - elf = load_elf(args->elffile); - if (!elf) - { - fprintf(stderr, "Loading ELF %s failure.\n", args->elffile); - exit(EXIT_FAILURE); +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); + + 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 5c1b979c04ba8..8cdac1185a4aa 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/mpconfigport.mk b/ports/cxd56/mpconfigport.mk index e1ffc79d089fd..e767c6326f506 100644 --- a/ports/cxd56/mpconfigport.mk +++ b/ports/cxd56/mpconfigport.mk @@ -7,8 +7,17 @@ USB_CDC_EP_NUM_DATA_IN = 1 USB_MSC_EP_NUM_OUT = 5 USB_MSC_EP_NUM_IN = 4 +# Number of USB endpoint pairs. +USB_NUM_EP = 6 + +# Define an equivalent for MICROPY_LONGINT_IMPL, to pass to $(MPY-TOOL) in py/mkrules.mk +# $(MPY-TOOL) needs to know what kind of longint to use (if any) to freeze long integers. +# This should correspond to the MICROPY_LONGINT_IMPL definition in mpconfigport.h. MPY_TOOL_LONGINT_IMPL = -mlongint-impl=mpz +# Longints can be implemented as mpz, as longlong, or not +LONGINT_IMPL = MPZ + CIRCUITPY_AUDIOBUSIO = 0 CIRCUITPY_AUDIOIO = 0 CIRCUITPY_CAMERA = 1 diff --git a/ports/cxd56/mphalport.h b/ports/cxd56/mphalport.h index 50e805cf505ea..ba5ca39b97996 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 523d6a496b2f0..fa7591918d8a0 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 840f10c32f5ad..a61342e3eae60 100755 --- a/ports/cxd56/tools/flash_writer.py +++ b/ports/cxd56/tools/flash_writer.py @@ -49,17 +49,17 @@ # 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 @@ # 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') - - 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("-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") - - 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_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") - - 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") - - def update_config(self): - args = self.parser.parse_args() - - 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 - - # 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: - 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 == None: - ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL - - 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.xmodem_baud is not None: - ConfigArgs.XMODEM_BAUD = args.xmodem_baud - - if args.auto_reset is not None: - ConfigArgs.AUTO_RESET = args.auto_reset - - 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 + +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", + ) + + 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( + "-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", + ) + + 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_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", + ) + + 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", + ) + + def update_config(self): + args = self.parser.parse_args() + + 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 + + # 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: + 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 == None: + ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL + + 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.xmodem_baud is not None: + ConfigArgs.XMODEM_BAUD = args.xmodem_baud + + if args.auto_reset is not None: + ConfigArgs.AUTO_RESET = args.auto_reset + + 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 + 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 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 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 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 reboot(self): - # no-op - pass - - 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 __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 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 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 putc(self, buffer, timeout=1): + self.telnet.write(buffer) + self.show_progress(len(buffer)) + + def reboot(self): + # no-op + pass + + 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") + 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 readline(self, size=None): - return self.serial.readline(size) - - 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 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)) - - # 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 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 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 __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 write(self, buffer): + self.serial.write(buffer) + self.serial.flush() + + 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 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 + + 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 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") + class FlashWriter: - 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 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_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 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 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_binary(self, bin_name) : - self.send("rm " + bin_name) - self.wait_for_prompt() + 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 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_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 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 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_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 - - # 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() - - 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 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) - - # 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) - - # 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() - - if REBOOT_AT_END : - print("Restarting the board ...") - writer.send("reboot") - - return 0 + try: + config_loader = ConfigArgsLoader() + config_loader.update_config() + except: + return errno.EINVAL + + # 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() + + 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 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) + + # 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) + + # 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() + + if REBOOT_AT_END: + print("Restarting the board ...") + writer.send("reboot") + + 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 c934300560c94..cf78338645151 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 @@ <-- 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 @@ import collections # Loggerr -log = logging.getLogger('xmodem') +log = logging.getLogger("xmodem") # Protocol bytes SOH = bytes([0x01]) @@ -130,11 +129,11 @@ 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 @@ def send(self, stream, retry=32, timeout=360, quiet=0, callback=None): 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 @@ def callback(total_packets, success_count, error_count) 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 @@ def callback(total_packets, success_count, error_count) 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 @@ def callback(total_packets, success_count, error_count) 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 @@ def callback(total_packets, success_count, error_count) # 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 @@ def callback(total_packets, success_count, error_count) # 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 @@ def callback(total_packets, success_count, error_count) # protocol error self.abort(timeout=timeout) - log.error('protocol error') + log.error("protocol error") return False # keep track of sequence @@ -353,7 +572,7 @@ def callback(total_packets, success_count, error_count) # 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 @@ def callback(total_packets, success_count, error_count) 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 @@ def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): Returns the number of bytes received on success or ``None`` in case of failure. - ''' + """ # initiate protocol error_count = 0 @@ -403,7 +622,7 @@ def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): error_count += 1 continue elif char == SOH: - #crc_mode = 0 + # crc_mode = 0 break elif char == STX: break @@ -442,7 +661,7 @@ def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): 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 @@ def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): 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 @@ def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): 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 @@ def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): 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 @@ def calc_checksum(self, data, checksum=0): >>> 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 @@ def calc_crc(self, data, crc=0): >>> 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 putc(data, timeout=3): 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/Makefile b/ports/esp32s2/Makefile index aac93478240da..bd79fe383cd87 100644 --- a/ports/esp32s2/Makefile +++ b/ports/esp32s2/Makefile @@ -164,7 +164,9 @@ LIBS += -lm endif # TinyUSB defines -CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32S2 -DCFG_TUSB_OS=OPT_OS_FREERTOS -DCFG_TUD_CDC_RX_BUFSIZE=1024 -DCFG_TUD_CDC_TX_BUFSIZE=1024 -DCFG_TUD_MSC_BUFSIZE=4096 -DCFG_TUD_MIDI_RX_BUFSIZE=128 -DCFG_TUD_MIDI_TX_BUFSIZE=128 +CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32S2 -DCFG_TUSB_OS=OPT_OS_FREERTOS -DCFG_TUD_CDC_RX_BUFSIZE=1024 -DCFG_TUD_CDC_TX_BUFSIZE=1024 +CFLAGS += -DCFG_TUD_MSC_BUFSIZE=4096 -DCFG_TUD_MIDI_RX_BUFSIZE=128 -DCFG_TUD_MIDI_TX_BUFSIZE=128 +CFLAGS += -DCFG_TUD_VENDOR_RX_BUFSIZE=128 -DCFG_TUD_VENDOR_TX_BUFSIZE=128 ###################################### @@ -199,7 +201,7 @@ SRC_C += \ peripherals/rmt.c \ supervisor/shared/memory.c -ifneq ($(USB),FALSE) +ifneq ($(CIRCUITPY_USB),0) SRC_C += lib/tinyusb/src/portable/espressif/esp32s2/dcd_esp32s2.c endif diff --git a/ports/esp32s2/background.c b/ports/esp32s2/background.c index 3160d9974e3e5..80b60bebe3505 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 708c30c391b58..97e1136f87cef 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 9248b01acd169..866edb1288dee 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 aaef97c7d1404..e40b6335bcb96 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 9d95e8e437ab8..a04065d25bea4 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 c8be187470209..799494006d175 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 9d95e8e437ab8..a04065d25bea4 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 7e1a72374273f..0504f9694e13e 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_funhouse/board.c b/ports/esp32s2/boards/adafruit_funhouse/board.c new file mode 100644 index 0000000000000..810b61dbe0dd9 --- /dev/null +++ b/ports/esp32s2/boards/adafruit_funhouse/board.c @@ -0,0 +1,123 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/displayio/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +#include "esp_log.h" + +displayio_fourwire_obj_t board_display_obj; + +#define DELAY 0x80 + +uint8_t display_init_sequence[] = { + 0x01, 0 | DELAY, 150, // SWRESET + 0x11, 0 | DELAY, 255, // SLPOUT + 0x36, 1, 0b10100000, // _MADCTL for rotation 0 + 0x3a, 1, 0x55, // COLMOD - 16bit color + 0x21, 0 | DELAY, 10, // _INVON + 0x13, 0 | DELAY, 10, // _NORON + 0x29, 0 | DELAY, 255, // _DISPON +}; + +void board_init(void) { + // USB + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); + + // Debug UART +#ifdef DEBUG + common_hal_never_reset_pin(&pin_GPIO37); + common_hal_never_reset_pin(&pin_GPIO38); +#endif /* DEBUG */ + + 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; + bus->base.type = &displayio_fourwire_type; + common_hal_displayio_fourwire_construct(bus, + spi, + &pin_GPIO39, // TFT_DC Command or data + &pin_GPIO40, // TFT_CS Chip select + &pin_GPIO41, // TFT_RESET Reset + 60000000, // Baudrate + 0, // Polarity + 0); // Phase + + // workaround as board_init() is called before reset_port() in main.c + pwmout_reset(); + + displayio_display_obj_t* display = &displays[0].display; + display->base.type = &displayio_display_type; + common_hal_displayio_display_construct( + display, + bus, + 240, // Width (after rotation) + 240, // Height (after rotation) + 80, // column start + 0, // row start + 270, // rotation + 16, // Color depth + false, // Grayscale + false, // Pixels in a byte share a row. Only used for depth < 8 + 1, // bytes per cell. Only valid for depths < 8 + false, // reverse_pixels_in_byte. Only valid for depths < 8 + true, // reverse_pixels_in_word + MIPI_COMMAND_SET_COLUMN_ADDRESS, // Set column command + MIPI_COMMAND_SET_PAGE_ADDRESS, // Set row command + MIPI_COMMAND_WRITE_MEMORY_START, // Write memory command + 0x37, // set vertical scroll command + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO21, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness (ignored) + true, // auto_brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false); // not SH1107 +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} + +void board_deinit(void) { +} diff --git a/ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h b/ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h new file mode 100644 index 0000000000000..99cb0982c90fb --- /dev/null +++ b/ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.h @@ -0,0 +1,42 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +//Micropython setup + +#define MICROPY_HW_BOARD_NAME "Adafruit FunHome" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define MICROPY_HW_APA_MOSI (&pin_GPIO14) +#define MICROPY_HW_APA_SCK (&pin_GPIO15) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing boot button at start up.\n") + +#define AUTORESET_DELAY_MS 500 + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO33) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO34) diff --git a/ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.mk b/ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.mk new file mode 100644 index 0000000000000..b71ff9e558af3 --- /dev/null +++ b/ports/esp32s2/boards/adafruit_funhouse/mpconfigboard.mk @@ -0,0 +1,17 @@ +USB_VID = 0x239A +USB_PID = 0x80FA +USB_PRODUCT = "FunHouse" +USB_MANUFACTURER = "Adafruit" + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_ESP_FLASH_MODE=dio +CIRCUITPY_ESP_FLASH_FREQ=40m +CIRCUITPY_ESP_FLASH_SIZE=4MB + +CIRCUITPY_MODULE=wrover diff --git a/ports/esp32s2/boards/adafruit_funhouse/pins.c b/ports/esp32s2/boards/adafruit_funhouse/pins.c new file mode 100644 index 0000000000000..9728512c0e21b --- /dev/null +++ b/ports/esp32s2/boards/adafruit_funhouse/pins.c @@ -0,0 +1,51 @@ +#include "shared-bindings/board/__init__.h" + +#include "shared-module/displayio/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + + { MP_ROM_QSTR(MP_QSTR_TFT_BACKLIGHT), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_TFT_MOSI), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_TFT_SCK), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON_DOWN), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_SELECT), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_UP), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_CAP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_CAP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_CAP8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_CAP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_CAP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_CAP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_CAP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_CAP13), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_DOTSTAR_DATA), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_DOTSTAR_CLOCK), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_PIR_SENSE), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_LIGHT), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_SPEAKER), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO34) }, + + { MP_OBJ_NEW_QSTR(MP_QSTR_DEBUG_TX), MP_ROM_PTR(&pin_GPIO37) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_DEBUG_RX), MP_ROM_PTR(&pin_GPIO38) }, + + { 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_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/adafruit_funhouse/sdkconfig b/ports/esp32s2/boards/adafruit_funhouse/sdkconfig new file mode 100644 index 0000000000000..9d8bbde967ded --- /dev/null +++ b/ports/esp32s2/boards/adafruit_funhouse/sdkconfig @@ -0,0 +1,33 @@ +CONFIG_ESP32S2_SPIRAM_SUPPORT=y + +# +# SPI RAM config +# +# CONFIG_SPIRAM_TYPE_AUTO is not set +CONFIG_SPIRAM_TYPE_ESPPSRAM16=y +# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM64 is not set +CONFIG_SPIRAM_SIZE=2097152 + +# +# PSRAM clock and cs IO for ESP32S2 +# +CONFIG_DEFAULT_PSRAM_CLK_IO=30 +CONFIG_DEFAULT_PSRAM_CS_IO=26 +# end of PSRAM clock and cs IO for ESP32S2 + +# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set +# CONFIG_SPIRAM_RODATA is not set +# CONFIG_SPIRAM_SPEED_80M is not set +CONFIG_SPIRAM_SPEED_40M=y +# CONFIG_SPIRAM_SPEED_26M is not set +# CONFIG_SPIRAM_SPEED_20M is not set +CONFIG_SPIRAM=y +CONFIG_SPIRAM_BOOT_INIT=y +# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set +CONFIG_SPIRAM_USE_MEMMAP=y +# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set +# CONFIG_SPIRAM_USE_MALLOC is not set +CONFIG_SPIRAM_MEMTEST=y +# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set +# end of SPI RAM config 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 63a16c1206582..020e6f6a1f56d 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 8dfe91271262d..ecfa1d78b3d1e 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 b25d7d1169bc5..ec992383aa486 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/artisense_rd00/board.c b/ports/esp32s2/boards/artisense_rd00/board.c new file mode 100644 index 0000000000000..fb3e458cf420e --- /dev/null +++ b/ports/esp32s2/boards/artisense_rd00/board.c @@ -0,0 +1,59 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Matthias Breithaupt for Artisense GmbH + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +void board_init(void) { + // USB + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); + + // Debug UART +#ifdef DEBUG + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); +#endif /* DEBUG */ + + // Crystal + common_hal_never_reset_pin(&pin_GPIO15); + common_hal_never_reset_pin(&pin_GPIO16); + + // PSRAM + common_hal_never_reset_pin(&pin_GPIO26); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} + +void board_deinit(void) { +} diff --git a/ports/esp32s2/boards/artisense_rd00/mpconfigboard.h b/ports/esp32s2/boards/artisense_rd00/mpconfigboard.h new file mode 100644 index 0000000000000..e9ff39dbbd79c --- /dev/null +++ b/ports/esp32s2/boards/artisense_rd00/mpconfigboard.h @@ -0,0 +1,43 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Matthias Breithaupt for Artisense GmbH + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +//Micropython setup + +//Same setup as the Saola board but with no Neopixel on board + +#define MICROPY_HW_BOARD_NAME "Artisense Reference Design RD00" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO45) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing boot button at start up.\n") + +#define AUTORESET_DELAY_MS 500 + +#define DEFAULT_UART_BUS_RX (&pin_GPIO17) +#define DEFAULT_UART_BUS_TX (&pin_GPIO18) diff --git a/ports/esp32s2/boards/artisense_rd00/mpconfigboard.mk b/ports/esp32s2/boards/artisense_rd00/mpconfigboard.mk new file mode 100644 index 0000000000000..8b6bfcb8d9a12 --- /dev/null +++ b/ports/esp32s2/boards/artisense_rd00/mpconfigboard.mk @@ -0,0 +1,17 @@ +USB_VID = 0x303A +USB_PID = 0x80AF +USB_PRODUCT = "Reference Design RD00" +USB_MANUFACTURER = "Artisense" + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_ESP_FLASH_MODE=dio +CIRCUITPY_ESP_FLASH_FREQ=40m +CIRCUITPY_ESP_FLASH_SIZE=4MB + +CIRCUITPY_MODULE=wrover diff --git a/ports/esp32s2/boards/artisense_rd00/pins.c b/ports/esp32s2/boards/artisense_rd00/pins.c new file mode 100644 index 0000000000000..3cd05f5b3c261 --- /dev/null +++ b/ports/esp32s2/boards/artisense_rd00/pins.c @@ -0,0 +1,48 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_CAM), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_HVIO0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_HVIO1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_HVIO2), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_HVIO3), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_HVIO4), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_HVCAM), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_LVIO0), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_LVIO1), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_LVIO2), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_LVIO3), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LVIO4), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_LVCAM), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_DIRIO0), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_DIRIO1), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_DIRIO2), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_DIRIO3), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_DIRIO4), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_DIRCAM), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_DBG_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_DBG_RX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_RS232_TX), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_RS232_RX), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_RS232_EN), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_DFU), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_SW1), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO45) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/artisense_rd00/sdkconfig b/ports/esp32s2/boards/artisense_rd00/sdkconfig new file mode 100644 index 0000000000000..b5bf2411f74bf --- /dev/null +++ b/ports/esp32s2/boards/artisense_rd00/sdkconfig @@ -0,0 +1,39 @@ +CONFIG_ESP32S2_SPIRAM_SUPPORT=y + +# +# SPI RAM config +# +# CONFIG_SPIRAM_TYPE_AUTO is not set +CONFIG_SPIRAM_TYPE_ESPPSRAM16=y +# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM64 is not set +CONFIG_SPIRAM_SIZE=2097152 + +# +# PSRAM clock and cs IO for ESP32S2 +# +CONFIG_DEFAULT_PSRAM_CLK_IO=30 +CONFIG_DEFAULT_PSRAM_CS_IO=26 +# end of PSRAM clock and cs IO for ESP32S2 + +# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set +# CONFIG_SPIRAM_RODATA is not set +# CONFIG_SPIRAM_SPEED_80M is not set +CONFIG_SPIRAM_SPEED_40M=y +# CONFIG_SPIRAM_SPEED_26M is not set +# CONFIG_SPIRAM_SPEED_20M is not set +CONFIG_SPIRAM=y +CONFIG_SPIRAM_BOOT_INIT=y +# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set +CONFIG_SPIRAM_USE_MEMMAP=y +# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set +# CONFIG_SPIRAM_USE_MALLOC is not set +CONFIG_SPIRAM_MEMTEST=y +# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set +# end of SPI RAM config + +# +# LWIP +# +CONFIG_LWIP_LOCAL_HOSTNAME="RD00-ESP32S2" +# end of LWIP diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/board.c b/ports/esp32s2/boards/atmegazero_esp32s2/board.c new file mode 100644 index 0000000000000..d8fd3a0a2b7bb --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/board.c @@ -0,0 +1,61 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +void board_init(void) { + // USB + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); + + // Debug UART +#ifdef DEBUG + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); +#endif /* DEBUG */ + + // SPI Flash and RAM + common_hal_never_reset_pin(&pin_GPIO26); + common_hal_never_reset_pin(&pin_GPIO27); + common_hal_never_reset_pin(&pin_GPIO28); + common_hal_never_reset_pin(&pin_GPIO29); + common_hal_never_reset_pin(&pin_GPIO30); + common_hal_never_reset_pin(&pin_GPIO31); + common_hal_never_reset_pin(&pin_GPIO32); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} + +void board_deinit(void) { +} diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h new file mode 100644 index 0000000000000..3ef4e7eede78f --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.h @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +//Micropython setup + +#define MICROPY_HW_BOARD_NAME "ATMegaZero ESP32-S2" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing boot button at start up.\n") + +#define AUTORESET_DELAY_MS 500 + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO9) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO8) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO36) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO35) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO37) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO40) diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.mk b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.mk new file mode 100644 index 0000000000000..9a5d947e6c6ca --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/mpconfigboard.mk @@ -0,0 +1,15 @@ +USB_VID = 0x239A +USB_PID = 0x8009 +USB_PRODUCT = "ATMegaZero ESP32-S2" +USB_MANUFACTURER = "ATMegaZero" + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_ESP_FLASH_MODE=qio +CIRCUITPY_ESP_FLASH_FREQ=40m +CIRCUITPY_ESP_FLASH_SIZE=16MB diff --git a/ports/esp32s2/boards/atmegazero_esp32s2/pins.c b/ports/esp32s2/boards/atmegazero_esp32s2/pins.c new file mode 100644 index 0000000000000..cfc4ef6223f2d --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/pins.c @@ -0,0 +1,80 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_IO44), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_PD5), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_HWD), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_DAC2), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + { 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/esp32s2/boards/atmegazero_esp32s2/sdkconfig b/ports/esp32s2/boards/atmegazero_esp32s2/sdkconfig new file mode 100644 index 0000000000000..f42e0784c4eb0 --- /dev/null +++ b/ports/esp32s2/boards/atmegazero_esp32s2/sdkconfig @@ -0,0 +1,39 @@ +CONFIG_ESP32S2_SPIRAM_SUPPORT=y + +# +# SPI RAM config +# +# CONFIG_SPIRAM_TYPE_AUTO is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM16 is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set +CONFIG_SPIRAM_TYPE_ESPPSRAM64=y +CONFIG_SPIRAM_SIZE=8388608 + +# +# PSRAM clock and cs IO for ESP32S2 +# +CONFIG_DEFAULT_PSRAM_CLK_IO=30 +CONFIG_DEFAULT_PSRAM_CS_IO=26 +# end of PSRAM clock and cs IO for ESP32S2 + +# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set +# CONFIG_SPIRAM_RODATA is not set +# CONFIG_SPIRAM_SPEED_80M is not set +CONFIG_SPIRAM_SPEED_40M=y +# CONFIG_SPIRAM_SPEED_26M is not set +# CONFIG_SPIRAM_SPEED_20M is not set +CONFIG_SPIRAM=y +CONFIG_SPIRAM_BOOT_INIT=y +# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set +CONFIG_SPIRAM_USE_MEMMAP=y +# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set +# CONFIG_SPIRAM_USE_MALLOC is not set +CONFIG_SPIRAM_MEMTEST=y +# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set +# end of SPI RAM config + +# +# LWIP +# +CONFIG_LWIP_LOCAL_HOSTNAME="ATMegaZero-Esp32s2" +# end of LWIP diff --git a/ports/esp32s2/boards/electroniccats_bastwifi/board.c b/ports/esp32s2/boards/electroniccats_bastwifi/board.c index aaef97c7d1404..e40b6335bcb96 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 1ec61e9461e2e..cc4fd40df2f8d 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 aaef97c7d1404..e40b6335bcb96 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 2c0f175abf18f..21f6ae2456703 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_kaluga_1/mpconfigboard.mk b/ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.mk index 2dce0388199f8..52c63cb9c712c 100644 --- a/ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.mk +++ b/ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.mk @@ -14,4 +14,10 @@ CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB +# We only have enough endpoints available in hardware to +# enable ONE of these at a time. +CIRCUITPY_USB_MIDI = 1 +CIRCUITPY_USB_HID = 0 +CIRCUITPY_USB_VENDOR = 0 + CIRCUITPY_MODULE=wrover diff --git a/ports/esp32s2/boards/espressif_saola_1_wroom/board.c b/ports/esp32s2/boards/espressif_saola_1_wroom/board.c index aaef97c7d1404..e40b6335bcb96 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 3f628c0f1e07f..2aac10fe79e37 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 aaef97c7d1404..e40b6335bcb96 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 9615228910da7..a5aa83814de7f 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 new file mode 100644 index 0000000000000..e40b6335bcb96 --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wroom/board.c @@ -0,0 +1,52 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +void board_init(void) { + // USB + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); + + // Debug UART + #ifdef DEBUG + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); + #endif /* DEBUG */ +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} + +void board_deinit(void) { +} diff --git a/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h b/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h new file mode 100644 index 0000000000000..c0a8659b1d277 --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h @@ -0,0 +1,38 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Franzininho WIFI w/Wroom" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO18) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing boot button at start up.\n") + +#define AUTORESET_DELAY_MS 500 diff --git a/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.mk b/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.mk new file mode 100644 index 0000000000000..fc6c62257af0b --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.mk @@ -0,0 +1,17 @@ +USB_VID = 0x303A +USB_PID = 0x80AA +USB_PRODUCT = "Franzininho WIFI w/Wroom" +USB_MANUFACTURER = "Espressif" + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_ESP_FLASH_MODE=dio +CIRCUITPY_ESP_FLASH_FREQ=40m +CIRCUITPY_ESP_FLASH_SIZE=4MB + +CIRCUITPY_MODULE=wroom diff --git a/ports/esp32s2/boards/franzininho_wifi_wroom/pins.c b/ports/esp32s2/boards/franzininho_wifi_wroom/pins.c new file mode 100644 index 0000000000000..0562d9331f46f --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wroom/pins.c @@ -0,0 +1,48 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + + + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_IO19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_IO20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_IO44), MP_ROM_PTR(&pin_GPIO44) }, + { 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_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/franzininho_wifi_wroom/sdkconfig b/ports/esp32s2/boards/franzininho_wifi_wroom/sdkconfig new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/esp32s2/boards/franzininho_wifi_wrover/board.c b/ports/esp32s2/boards/franzininho_wifi_wrover/board.c new file mode 100644 index 0000000000000..e40b6335bcb96 --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wrover/board.c @@ -0,0 +1,52 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +void board_init(void) { + // USB + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); + + // Debug UART + #ifdef DEBUG + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); + #endif /* DEBUG */ +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} + +void board_deinit(void) { +} diff --git a/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h b/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h new file mode 100644 index 0000000000000..b17a65c10ce60 --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h @@ -0,0 +1,38 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Franzininho WIFI w/Wrover" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO18) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing boot button at start up.\n") + +#define AUTORESET_DELAY_MS 500 diff --git a/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.mk b/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.mk new file mode 100644 index 0000000000000..c0c47cef10a16 --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.mk @@ -0,0 +1,17 @@ +USB_VID = 0x303A +USB_PID = 0x80AD +USB_PRODUCT = "Franzininho WIFI w/Wrover" +USB_MANUFACTURER = "Espressif" + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_ESP_FLASH_MODE=dio +CIRCUITPY_ESP_FLASH_FREQ=40m +CIRCUITPY_ESP_FLASH_SIZE=4MB + +CIRCUITPY_MODULE=wrover diff --git a/ports/esp32s2/boards/franzininho_wifi_wrover/pins.c b/ports/esp32s2/boards/franzininho_wifi_wrover/pins.c new file mode 100644 index 0000000000000..0562d9331f46f --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wrover/pins.c @@ -0,0 +1,48 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + + + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_IO19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_IO20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_IO44), MP_ROM_PTR(&pin_GPIO44) }, + { 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_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/franzininho_wifi_wrover/sdkconfig b/ports/esp32s2/boards/franzininho_wifi_wrover/sdkconfig new file mode 100644 index 0000000000000..9d8bbde967ded --- /dev/null +++ b/ports/esp32s2/boards/franzininho_wifi_wrover/sdkconfig @@ -0,0 +1,33 @@ +CONFIG_ESP32S2_SPIRAM_SUPPORT=y + +# +# SPI RAM config +# +# CONFIG_SPIRAM_TYPE_AUTO is not set +CONFIG_SPIRAM_TYPE_ESPPSRAM16=y +# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM64 is not set +CONFIG_SPIRAM_SIZE=2097152 + +# +# PSRAM clock and cs IO for ESP32S2 +# +CONFIG_DEFAULT_PSRAM_CLK_IO=30 +CONFIG_DEFAULT_PSRAM_CS_IO=26 +# end of PSRAM clock and cs IO for ESP32S2 + +# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set +# CONFIG_SPIRAM_RODATA is not set +# CONFIG_SPIRAM_SPEED_80M is not set +CONFIG_SPIRAM_SPEED_40M=y +# CONFIG_SPIRAM_SPEED_26M is not set +# CONFIG_SPIRAM_SPEED_20M is not set +CONFIG_SPIRAM=y +CONFIG_SPIRAM_BOOT_INIT=y +# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set +CONFIG_SPIRAM_USE_MEMMAP=y +# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set +# CONFIG_SPIRAM_USE_MALLOC is not set +CONFIG_SPIRAM_MEMTEST=y +# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set +# end of SPI RAM config 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 aaef97c7d1404..1002fa6b7674e 100644 --- a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/board.c +++ b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/board.c @@ -27,6 +27,109 @@ #include "supervisor/board.h" #include "mpconfigboard.h" #include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +#define DELAY 0x80 + +// display init sequence according to LilyGO example app +uint8_t display_init_sequence[] = { + // sw reset + 0x01, 0 | DELAY, 150, + // sleep out + 0x11, 0 | DELAY, 255, + // normal display mode on + 0x13, 0, + // display and color format settings + 0x36, 1, 0x08, + 0xB6, 2, 0x0A, 0x82, + 0x3A, 1 | DELAY, 0x55, 10, + // ST7789V frame rate setting + 0xB2, 5, 0x0C, 0x0C, 0x00, 0x33, 0x33, + // voltages: VGH / VGL + 0xB7, 1, 0x35, + // ST7789V power setting + 0xBB, 1, 0x28, + 0xC0, 1, 0x0C, + 0xC2, 2, 0x01, 0xFF, + 0xC3, 1, 0x10, + 0xC4, 1, 0x20, + 0xC6, 1, 0x0F, + 0xD0, 2, 0xA4, 0xA1, + // ST7789V gamma setting + 0xE0, 14, 0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x32, 0x44, 0x42, 0x06, 0x0E, 0x12, 0x14, 0x17, + 0xE1, 14, 0xD0, 0x00, 0x02, 0x07, 0x0A, 0x28, 0x31, 0x54, 0x47, 0x0E, 0x1C, 0x17, 0x1B, 0x1E, + 0x21, 0, + // display on + 0x29, 0 | DELAY, 255, +}; + +static void display_init(void) { + 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; + bus->base.type = &displayio_fourwire_type; + + common_hal_displayio_fourwire_construct( + bus, + spi, + &pin_GPIO37, // DC + &pin_GPIO34, // CS + &pin_GPIO38, // RST + 40000000, // baudrate + 0, // polarity + 0 // phase + ); + + 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 + pwmout_reset(); + + common_hal_displayio_display_construct( + display, + bus, + 240, // width (after rotation) + 135, // height (after rotation) + 52, // column start + 40, // row start + 90, // rotation + 16, // color depth + false, // grayscale + false, // pixels in a byte share a row. Only valid for depths < 8 + 1, // bytes per cell. Only valid for depths < 8 + false, // reverse_pixels_in_byte. Only valid for depths < 8 + true, // reverse_pixels_in_word + MIPI_COMMAND_SET_COLUMN_ADDRESS, // set column command + MIPI_COMMAND_SET_PAGE_ADDRESS, // set row command + MIPI_COMMAND_WRITE_MEMORY_START, // write memory command + 0x37, // set vertical scroll command + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO33, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness (ignored) + false, // auto_brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false // SH1107_addressing + ); + + common_hal_never_reset_pin(&pin_GPIO33); // backlight pin +} void board_init(void) { // USB @@ -34,10 +137,13 @@ 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(); } bool board_requests_safe_mode(void) { 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 c9020c2002035..c9159b6f32b3b 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/lilygo_ttgo_t8_s2_st7789/mpconfigboard.mk b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.mk index 38a7ed1fb7bda..79b45fd92c11f 100644 --- a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.mk +++ b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.mk @@ -2,7 +2,6 @@ USB_VID = 0x303a USB_PID = 0x8007 USB_PRODUCT = "TTGO T8 ESP32-S2" USB_MANUFACTURER = "LILYGO" -USB_DEVICES = "CDC,MSC,HID" INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = MPZ diff --git a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/pins.c b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/pins.c index bda0fd227acc1..a30c6797a5b9d 100644 --- a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/pins.c +++ b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/pins.c @@ -1,4 +1,5 @@ #include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, @@ -41,13 +42,13 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO10) }, // 1.14 inch LCD ST7789 - { MP_ROM_QSTR(MP_QSTR_LCD_MISO), MP_ROM_PTR(&pin_GPIO4) }, { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO35) }, { MP_ROM_QSTR(MP_QSTR_LCD_CLK), MP_ROM_PTR(&pin_GPIO36) }, { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO34) }, { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_GPIO38) }, { MP_ROM_QSTR(MP_QSTR_LCD_BCKL), MP_ROM_PTR(&pin_GPIO33) }, { MP_ROM_QSTR(MP_QSTR_LCD_D_C), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display) }, // Peripheral Power control { MP_ROM_QSTR(MP_QSTR_PE_POWER), MP_ROM_PTR(&pin_GPIO14) }, diff --git a/ports/esp32s2/boards/microdev_micro_s2/board.c b/ports/esp32s2/boards/microdev_micro_s2/board.c index d8fd3a0a2b7bb..a0e399b1efe59 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 272ab20fa5112..47bcde7e93904 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/microdev_micro_s2/mpconfigboard.mk b/ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.mk index 515617095775d..783e7ad4c7ac8 100644 --- a/ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.mk +++ b/ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.mk @@ -2,7 +2,6 @@ USB_VID = 0x239A USB_PID = 0x80C6 USB_PRODUCT = "microS2" USB_MANUFACTURER = "microDev" -USB_DEVICES = "CDC,MSC,HID" INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = MPZ diff --git a/ports/esp32s2/boards/muselab_nanoesp32_s2/board.c b/ports/esp32s2/boards/muselab_nanoesp32_s2/board.c index aaef97c7d1404..e40b6335bcb96 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 6b05ac06f4001..1612153976da6 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 9c58dd2c8a1e3..00b94a0259eda 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 6cf69138e7a88..fe57007a9478b 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 99db09645732a..a8ca8ba3ed8d0 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 f5e66acb61579..00b94a0259eda 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 3c74d27fa4d53..c36ab50d11f97 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 99db09645732a..a8ca8ba3ed8d0 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 d8fd3a0a2b7bb..a0e399b1efe59 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 e100ac118efda..57f35018da92c 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/mpconfigboard.mk b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.mk index 9857c07617370..d045cc2149e88 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.mk +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.mk @@ -2,7 +2,6 @@ USB_VID = 0x239A USB_PID = 0x80AC USB_PRODUCT = "FeatherS2" USB_MANUFACTURER = "UnexpectedMaker" -USB_DEVICES = "CDC,MSC,HID" INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = MPZ diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c b/ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c index bef2001bac0ce..a4967992a8e3a 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/pins.c @@ -1,13 +1,15 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_global_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_DAC2), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO14) }, diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/board.c b/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/board.c index d8fd3a0a2b7bb..a0e399b1efe59 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 d550ff64fed4a..7304512aa8f2a 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_feathers2_prerelease/mpconfigboard.mk b/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.mk index 9857c07617370..d045cc2149e88 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.mk +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.mk @@ -2,7 +2,6 @@ USB_VID = 0x239A USB_PID = 0x80AC USB_PRODUCT = "FeatherS2" USB_MANUFACTURER = "UnexpectedMaker" -USB_DEVICES = "CDC,MSC,HID" INTERNAL_FLASH_FILESYSTEM = 1 LONGINT_IMPL = MPZ diff --git a/ports/esp32s2/boards/unexpectedmaker_tinys2/board.c b/ports/esp32s2/boards/unexpectedmaker_tinys2/board.c new file mode 100644 index 0000000000000..a0e399b1efe59 --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_tinys2/board.c @@ -0,0 +1,61 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +void board_init(void) { + // USB + common_hal_never_reset_pin(&pin_GPIO19); + common_hal_never_reset_pin(&pin_GPIO20); + + // Debug UART + #ifdef DEBUG + common_hal_never_reset_pin(&pin_GPIO43); + common_hal_never_reset_pin(&pin_GPIO44); + #endif /* DEBUG */ + + // SPI Flash and RAM + common_hal_never_reset_pin(&pin_GPIO26); + common_hal_never_reset_pin(&pin_GPIO27); + common_hal_never_reset_pin(&pin_GPIO28); + common_hal_never_reset_pin(&pin_GPIO29); + common_hal_never_reset_pin(&pin_GPIO30); + common_hal_never_reset_pin(&pin_GPIO31); + common_hal_never_reset_pin(&pin_GPIO32); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} + +void board_deinit(void) { +} diff --git a/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h b/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h new file mode 100644 index 0000000000000..e7d50f08945ca --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h @@ -0,0 +1,46 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "TinyS2" +#define MICROPY_HW_MCU_NAME "ESP32S2" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO1) +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing boot button at start up.\n") + +#define AUTORESET_DELAY_MS 500 + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO9) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO8) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO36) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO35) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO37) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) diff --git a/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.mk b/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.mk new file mode 100644 index 0000000000000..0d054c0cb0c78 --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.mk @@ -0,0 +1,20 @@ +USB_VID = 0x303A +USB_PID = 0x8002 +USB_PRODUCT = "TinyS2" +USB_MANUFACTURER = "UnexpectedMaker" + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = MPZ + +# The default queue depth of 16 overflows on release builds, +# so increase it to 32. +CFLAGS += -DCFG_TUD_TASK_QUEUE_SZ=32 + +CIRCUITPY_ESP_FLASH_MODE=qio +CIRCUITPY_ESP_FLASH_FREQ=80m +CIRCUITPY_ESP_FLASH_SIZE=4MB + +CIRCUITPY_BITBANG_NEOPIXEL = 1 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/esp32s2/boards/unexpectedmaker_tinys2/pins.c b/ports/esp32s2/boards/unexpectedmaker_tinys2/pins.c new file mode 100644 index 0000000000000..9815cf288d62f --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_tinys2/pins.c @@ -0,0 +1,92 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_DAC2), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_SDO), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_SDI), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO38) }, + + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + + { MP_ROM_QSTR(MP_QSTR_IO44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // Battery voltage sense pin + // I really don't know what name to use here. Adafruit use BATTERY & VOLTAGE_MONITOR + // I prefer VBAT or VBAT_SENSE + { MP_ROM_QSTR(MP_QSTR_BATTERY), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_VBAT), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_VBAT_SENSE), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO3) }, + + // 5V present sense pin + { MP_ROM_QSTR(MP_QSTR_VBUS), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO1) }, + + { 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/esp32s2/boards/unexpectedmaker_tinys2/sdkconfig b/ports/esp32s2/boards/unexpectedmaker_tinys2/sdkconfig new file mode 100644 index 0000000000000..91447cdc2a971 --- /dev/null +++ b/ports/esp32s2/boards/unexpectedmaker_tinys2/sdkconfig @@ -0,0 +1,39 @@ +CONFIG_ESP32S2_SPIRAM_SUPPORT=y + +# +# SPI RAM config +# +# CONFIG_SPIRAM_TYPE_AUTO=y +CONFIG_SPIRAM_TYPE_ESPPSRAM16=y +# CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set +# CONFIG_SPIRAM_TYPE_ESPPSRAM64=y +CONFIG_SPIRAM_SIZE=2097152 + +# +# PSRAM clock and cs IO for ESP32S2 +# +CONFIG_DEFAULT_PSRAM_CLK_IO=30 +CONFIG_DEFAULT_PSRAM_CS_IO=26 +# end of PSRAM clock and cs IO for ESP32S2 + +# CONFIG_SPIRAM_FETCH_INSTRUCTIONS is not set +# CONFIG_SPIRAM_RODATA is not set +# CONFIG_SPIRAM_SPEED_80M=y +CONFIG_SPIRAM_SPEED_40M=y +# CONFIG_SPIRAM_SPEED_26M is not set +# CONFIG_SPIRAM_SPEED_20M is not set +CONFIG_SPIRAM=y +CONFIG_SPIRAM_BOOT_INIT=y +# CONFIG_SPIRAM_IGNORE_NOTFOUND is not set +CONFIG_SPIRAM_USE_MEMMAP=y +# CONFIG_SPIRAM_USE_CAPS_ALLOC is not set +# CONFIG_SPIRAM_USE_MALLOC is not set +CONFIG_SPIRAM_MEMTEST=y +# CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY is not set +# end of SPI RAM config + +# +# LWIP +# +CONFIG_LWIP_LOCAL_HOSTNAME="UMTinyS2" +# end of LWIP diff --git a/ports/esp32s2/common-hal/alarm/SleepMemory.c b/ports/esp32s2/common-hal/alarm/SleepMemory.c index 38e3de2b6d0ee..b25bf28d25113 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/__init__.c b/ports/esp32s2/common-hal/alarm/__init__.c index 1cec5d4ae881f..63a19ab94811d 100644 --- a/ports/esp32s2/common-hal/alarm/__init__.c +++ b/ports/esp32s2/common-hal/alarm/__init__.c @@ -75,7 +75,7 @@ STATIC esp_sleep_wakeup_cause_t _get_wakeup_cause(void) { return esp_sleep_get_wakeup_cause(); } -bool alarm_woken_from_sleep(void) { +bool common_hal_alarm_woken_from_sleep(void) { return _get_wakeup_cause() != ESP_SLEEP_WAKEUP_UNDEFINED; } @@ -120,8 +120,8 @@ STATIC void _idle_until_alarm(void) { while (!mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; // Allow ctrl-C interrupt. - if (alarm_woken_from_sleep()) { - alarm_save_wake_alarm(); + if (common_hal_alarm_woken_from_sleep()) { + shared_alarm_save_wake_alarm(); return; } port_idle_until_interrupt(); @@ -147,14 +147,22 @@ void common_hal_alarm_set_deep_sleep_alarms(size_t n_alarms, const mp_obj_t *ala _setup_sleep_alarms(true, n_alarms, alarms); } -void NORETURN alarm_enter_deep_sleep(void) { +void NORETURN common_hal_alarm_enter_deep_sleep(void) { alarm_pin_pinalarm_prepare_for_deep_sleep(); alarm_touch_touchalarm_prepare_for_deep_sleep(); + + // Disable brownout detection, which appears to be triggered sometimes when + // waking from deep sleep. + // See https://www.esp32.com/viewtopic.php?f=13&t=19208#p71084 + // and https://github.com/adafruit/circuitpython/issues/4025#issuecomment-771027606 + // TODO: We can remove this workaround when ESP-IDF handles this. + CLEAR_PERI_REG_MASK(RTC_CNTL_BROWN_OUT_REG, RTC_CNTL_BROWN_OUT_RST_ENA); + // The ESP-IDF caches the deep sleep settings and applies them before sleep. // We don't need to worry about resetting them in the interim. esp_deep_sleep_start(); } void common_hal_alarm_gc_collect(void) { - gc_collect_ptr(alarm_get_wake_alarm()); + gc_collect_ptr(shared_alarm_get_wake_alarm()); } diff --git a/ports/esp32s2/common-hal/alarm/pin/PinAlarm.c b/ports/esp32s2/common-hal/alarm/pin/PinAlarm.c index df8d10ef9e544..9ccb5700cb169 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 deleted file mode 100644 index b39693c6af657..0000000000000 --- a/ports/esp32s2/common-hal/alarm/pin/__init__.c +++ /dev/null @@ -1,35 +0,0 @@ -#include "shared-bindings/alarm_io/__init__.h" - -#include "esp_sleep.h" -#include "driver/rtc_io.h" - -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) { - 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)) { - case ESP_ERR_INVALID_ARG: - mp_raise_ValueError(translate("trigger level must be 0 or 1")); - case ESP_ERR_INVALID_STATE: - mp_raise_RuntimeError(translate("wakeup conflict")); - default: - break; - } - - 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) { - 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 bcde0ab3c0e03..93e4f180914d0 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 3095bc9e8b22c..8c139afaf3433 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 b2c09fc076879..add4c3e14eb1d 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 b9c4866f295d9..8c1f8a2ffb237 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 080a01b047c76..589c477a7805f 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 6285151ba0a06..6dc823ce53dea 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 86322be8655fa..6548f46071cef 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); @@ -63,13 +63,16 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, self->bit_clock = bit_clock; self->word_select = word_select; self->data = data; + claim_pin(bit_clock); + claim_pin(word_select); + 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; } @@ -95,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 01c77c531356d..60d00aaa61b57 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 772262d0a5ef0..d97ccd9f156f1 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -53,10 +53,9 @@ void i2c_reset(void) { } } } -static bool i2c_inited[I2C_NUM_MAX]; 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. @@ -66,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); @@ -85,15 +84,14 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, if (gpio_get_level(sda->number) == 0 || gpio_get_level(scl->number) == 0) { reset_pin_number(sda->number); reset_pin_number(scl->number); - mp_raise_RuntimeError(translate("SDA or SCL needs a pull up")); + mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); } -#endif + #endif - if (xSemaphoreCreateBinaryStatic(&self->semaphore) != &self->semaphore) { + if (xSemaphoreCreateMutexStatic(&self->semaphore) != &self->semaphore) { mp_raise_RuntimeError(translate("Unable to create lock")); } - xSemaphoreGive(&self->semaphore); self->sda_pin = sda; self->scl_pin = scl; self->i2c_num = I2C_NUM_MAX; @@ -106,6 +104,10 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, mp_raise_ValueError(translate("All I2C peripherals are in use")); } i2c_status[self->i2c_num] = STATUS_IN_USE; + + // Delete any previous driver. + i2c_driver_delete(self->i2c_num); + i2c_config_t i2c_conf = { .mode = I2C_MODE_MASTER, .sda_io_num = self->sda_pin->number, @@ -117,23 +119,16 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, .clk_speed = frequency, } }; - esp_err_t result = i2c_param_config(self->i2c_num, &i2c_conf); - if (result != ESP_OK) { - mp_raise_ValueError(translate("Invalid pins")); + if (i2c_param_config(self->i2c_num, &i2c_conf) != ESP_OK) { + mp_raise_ValueError(translate("Invalid frequency")); } - - if (!i2c_inited[self->i2c_num]) { - result = i2c_driver_install(self->i2c_num, - I2C_MODE_MASTER, - 0, - 0, - 0); - if (result != ESP_OK) { - mp_raise_OSError(MP_EIO); - } - i2c_inited[self->i2c_num] = true; - + if (i2c_driver_install(self->i2c_num, + I2C_MODE_MASTER, + 0, + 0, + 0) != ESP_OK) { + mp_raise_OSError(MP_EIO); } claim_pin(sda); @@ -149,12 +144,14 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { return; } - i2c_status[self->i2c_num] = STATUS_FREE; + i2c_driver_delete(self->i2c_num); common_hal_reset_pin(self->sda_pin); common_hal_reset_pin(self->scl_pin); self->sda_pin = NULL; self->scl_pin = NULL; + + i2c_status[self->i2c_num] = STATUS_FREE; } bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { @@ -185,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); } @@ -205,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 1a989e30a42f3..9629e7b18ebd4 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 c4d54ec81c4b0..917b391112e44 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 d6203feae6e2e..488c0954ed4c6 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 98cebba67f821..7af43a476de20 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; } @@ -291,13 +291,14 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, mp_raise_ValueError(translate("No TX pin")); } - while (len > 0) { - int count = uart_tx_chars(self->uart_num, (const char*) data, len); + size_t left_to_write = len; + while (left_to_write > 0) { + int count = uart_tx_chars(self->uart_num, (const char *)data, left_to_write); if (count < 0) { *errcode = MP_EAGAIN; return MP_STREAM_ERROR; } - len -= count; + left_to_write -= count; data += count; RUN_BACKGROUND_TASKS; } @@ -322,7 +323,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 751fb2e002178..0d19221c8f28f 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 768fde2431dc2..720034755b117 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 85fb6972bea8f..82f30bc6f12ce 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 fddbfeb583b54..5e968f239382d 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 d24900e4357fb..cc8545e3751ff 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 fe52d93add4d4..bdc8b290fec02 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 b95b20d1534ea..d47de33e53c31 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 a2a0209f93a26..f2c40ce9ba886 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 f77b37b57cf67..cbe093164fa4c 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, uint32_t frequency) { 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 - */ - - - 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. - */ - - *(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 - - } - } + 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++) { + + /* 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 + + } + } } 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 84302118bda43..59eb64f34d05f 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 1414f131d1a91..04f5d6203d2e2 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 8b18336c948b4..eb325b9fb7113 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 12d612abb0ab7..cd13cddc66de8 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 fca89ce8ec000..5c00ca49e1f1d 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); } @@ -134,7 +134,7 @@ bool pin_number_is_free(gpio_num_t pin_number) { uint8_t offset = pin_number / 32; uint32_t mask = 1 << (pin_number % 32); - return (never_reset_pins[offset] & mask) == 0 && (in_use[offset] & mask) == 0; + return (in_use[offset] & mask) == 0; } bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.h b/ports/esp32s2/common-hal/microcontroller/Pin.h index f6c0087031c63..e7b488f048d33 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 fffd1a1b191e1..eb65f2d101a4a 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 e425cbf543b25..85eb0b522b18d 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 63d50bf14affa..89d90ae996447 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 71321e7e6536c..31308737929f7 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 44b63d7241df2..3bd5191fcd6dc 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 4d6a6a2bfcbd9..ee53bec04becb 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 003f0d827eac2..f4845b0fa865d 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 9feeea1479bdd..a9533179bb3ba 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 289605ed0521d..3afd8db250513 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 e45492a893596..d3490d1810b6e 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 e1fdd4760ae27..d662e1dbefb67 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) { @@ -92,8 +92,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, } } if (timer_index == INDEX_EMPTY) { - // Running out of timers isn't pin related on ESP32S2 so we can't re-use error messages - mp_raise_ValueError(translate("No more timers available")); + // Running out of timers isn't pin related on ESP32S2. + return PWMOUT_ALL_TIMERS_IN_USE; } // Find a viable channel @@ -104,7 +104,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, } } if (channel_index == INDEX_EMPTY) { - mp_raise_ValueError(translate("No more channels available")); + return PWMOUT_ALL_CHANNELS_IN_USE; } // Run configuration @@ -115,7 +115,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, self->tim_handle.clk_cfg = LEDC_AUTO_CLK; if (ledc_timer_config(&(self->tim_handle)) != ESP_OK) { - mp_raise_ValueError(translate("Could not initialize timer")); + return PWMOUT_INITIALIZATION_ERROR; } self->chan_handle.channel = channel_index; @@ -126,7 +126,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, self->chan_handle.timer_sel = timer_index; if (ledc_channel_config(&(self->chan_handle))) { - mp_raise_ValueError(translate("Could not initialize channel")); + return PWMOUT_INITIALIZATION_ERROR; } // Make reservations @@ -148,6 +148,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { never_reset_tim[self->tim_handle.timer_num] = true; never_reset_chan[self->chan_handle.channel] = true; + + never_reset_pin_number(self->pin_number); } void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { @@ -155,11 +157,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 +171,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 +188,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 9055dee8e35a5..9480b8885a250 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 25529ac723006..59fa54880ac1d 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 fc50ca3ab2599..7c6f66c82506a 100644 --- a/ports/esp32s2/common-hal/socketpool/Socket.c +++ b/ports/esp32s2/common-hal/socketpool/Socket.c @@ -3,7 +3,6 @@ * * The MIT License (MIT) * - * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries * Copyright (c) 2020 Lucian Copeland for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -38,23 +37,22 @@ #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]; // 4 on the wrover/wroom +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++) { if (open_socket_handles[i]) { if (open_socket_handles[i]->num > 0) { + // Close automatically clears socket handle common_hal_socketpool_socket_close(open_socket_handles[i]); - open_socket_handles[i] = NULL; } else { - // accidentally got a TCP socket in here, or something. open_socket_handles[i] = NULL; } } } } -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; @@ -64,73 +62,14 @@ bool register_open_socket(socketpool_socket_obj_t* self) { return false; } -STATIC void _lazy_init_LWIP(socketpool_socket_obj_t* self) { - if (self->num != -1) { - return; //safe to call on existing socket - } - if (self->tls != NULL) { - mp_raise_RuntimeError(translate("Invalid use of TLS Socket")); - } - int socknum = -1; - socknum = lwip_socket(self->family, self->type, self->ipproto); - if (socknum < 0 || !register_open_socket(self)) { - mp_raise_RuntimeError(translate("Out of sockets")); - } - self->num = socknum; - lwip_fcntl(socknum, F_SETFL, O_NONBLOCK); -} - -STATIC void _lazy_init_TLS(socketpool_socket_obj_t* self) { - if (self->type != SOCK_STREAM || self->num != -1) { - mp_raise_RuntimeError(translate("Invalid socket for TLS")); - } - esp_tls_t* tls_handle = esp_tls_init(); - if (tls_handle == NULL) { - mp_raise_espidf_MemoryError(); - } - self->tls = tls_handle; -} - -void common_hal_socketpool_socket_settimeout(socketpool_socket_obj_t* self, mp_uint_t timeout_ms) { - self->timeout_ms = timeout_ms; -} - -bool common_hal_socketpool_socket_bind(socketpool_socket_obj_t* self, - const char* host, size_t hostlen, uint8_t port) { - _lazy_init_LWIP(self); - - struct sockaddr_in bind_addr; - bind_addr.sin_addr.s_addr = inet_addr(host); - bind_addr.sin_family = AF_INET; - bind_addr.sin_port = htons(port); - - int opt = 1; - int err = lwip_setsockopt(self->num, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - if (err != 0) { - mp_raise_RuntimeError(translate("Issue setting SO_REUSEADDR")); - } - int result = lwip_bind(self->num, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) == 0; - return result; -} - -bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t* self, int backlog) { - return lwip_listen(self->num, backlog) == 0; -} - -socketpool_socket_obj_t* common_hal_socketpool_socket_accept(socketpool_socket_obj_t* self, - uint8_t* ip, uint *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; bool timed_out = false; uint64_t start_ticks = supervisor_ticks_ms64(); - if (self->timeout_ms != (uint)-1) { - mp_printf(&mp_plat_print, "will timeout"); - } else { - mp_printf(&mp_plat_print, "won't timeout"); - } - // Allow timeouts and interrupts while (newsoc == -1 && !timed_out && @@ -140,7 +79,7 @@ socketpool_socket_obj_t* common_hal_socketpool_socket_accept(socketpool_socket_o } RUN_BACKGROUND_TASKS; newsoc = lwip_accept(self->num, (struct sockaddr *)&accept_addr, &socklen); - // In non-blocking mode, fail instead of looping + // In non-blocking mode, fail instead of timing out if (newsoc == -1 && self->timeout_ms == 0) { mp_raise_OSError(MP_EAGAIN); } @@ -148,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); @@ -159,9 +98,8 @@ socketpool_socket_obj_t* common_hal_socketpool_socket_accept(socketpool_socket_o socketpool_socket_obj_t *sock = m_new_obj_with_finaliser(socketpool_socket_obj_t); sock->base.type = &socketpool_socket_type; sock->num = newsoc; - sock->tls = NULL; - sock->ssl_context = NULL; sock->pool = self->pool; + sock->connected = true; if (!register_open_socket(sock)) { mp_raise_OSError(MP_EBADF); @@ -175,72 +113,136 @@ socketpool_socket_obj_t* common_hal_socketpool_socket_accept(socketpool_socket_o } } -bool common_hal_socketpool_socket_connect(socketpool_socket_obj_t* self, - const char* host, mp_uint_t hostlen, mp_int_t port) { - // For simplicity we use esp_tls for all TCP connections. If it's not SSL, ssl_context will be - // NULL and should still work. This makes regular TCP connections more memory expensive but TLS - // should become more and more common. Therefore, we optimize for the TLS case. +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; + bind_addr.sin_port = htons(port); - // Todo: move to SSL Wrapper and add lwip_connect() - _lazy_init_TLS(self); + int opt = 1; + int err = lwip_setsockopt(self->num, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); + if (err != 0) { + mp_raise_RuntimeError(translate("Cannot set socket options")); + } + int result = lwip_bind(self->num, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) == 0; + return result; +} - esp_tls_cfg_t* tls_config = NULL; - if (self->ssl_context != NULL) { - tls_config = &self->ssl_context->ssl_config; +void common_hal_socketpool_socket_close(socketpool_socket_obj_t *self) { + self->connected = false; + if (self->num >= 0) { + lwip_shutdown(self->num, 0); + lwip_close(self->num); + self->num = -1; } - int result = esp_tls_conn_new_sync(host, hostlen, port, tls_config, self->tls); - self->connected = result >= 0; - if (result < 0) { - int esp_tls_code; - int flags; - esp_err_t err = esp_tls_get_and_clear_last_error(self->tls->error_handle, &esp_tls_code, &flags); - - if (err == ESP_ERR_MBEDTLS_SSL_SETUP_FAILED) { - mp_raise_espidf_MemoryError(); - } else if (ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED) { - mp_raise_OSError_msg_varg(translate("Failed SSL handshake")); - } else { - mp_raise_OSError_msg_varg(translate("Unhandled ESP TLS error %d %d %x %d"), esp_tls_code, flags, err, result); + // Remove socket record + for (size_t i = 0; i < MP_ARRAY_SIZE(open_socket_handles); i++) { + if (open_socket_handles[i] == self) { + open_socket_handles[i] = NULL; } + } +} + +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, + }; + struct addrinfo *result_i; + int error = lwip_getaddrinfo(host, NULL, &hints, &result_i); + if (error != 0 || result_i == NULL) { + mp_raise_OSError(EHOSTUNREACH); + } + + // Set parameters + struct sockaddr_in dest_addr; + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + dest_addr.sin_addr.s_addr = ((struct sockaddr_in *)result_i->ai_addr)->sin_addr.s_addr; + #pragma GCC diagnostic pop + freeaddrinfo(result_i); + + dest_addr.sin_family = AF_INET; + dest_addr.sin_port = htons(port); + + // Replace above with function call ----- + + // Switch to blocking mode for this one call + int opts; + opts = lwip_fcntl(self->num,F_GETFL,0); + opts = opts & (~O_NONBLOCK); + lwip_fcntl(self->num, F_SETFL, opts); + + int result = -1; + result = lwip_connect(self->num, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in)); + + // Switch back once complete + opts = opts | O_NONBLOCK; + lwip_fcntl(self->num, F_SETFL, opts); + + if (result >= 0) { + self->connected = true; + return true; } else { - // Connection successful, set the timeout on the underlying socket. We can't rely on the IDF - // to do it because the config structure is only used for TLS connections. Generally, we - // shouldn't hit this timeout because we try to only read available data. However, there is - // always a chance that we try to read something that is used internally. - int fd; - esp_tls_get_conn_sockfd(self->tls, &fd); - struct timeval tv; - tv.tv_sec = 2 * 60; // Two minutes - tv.tv_usec = 0; - setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + mp_raise_OSError(errno); } +} - return self->connected; +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; } -mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t* self, const uint8_t* buf, mp_uint_t len) { - int sent = -1; - if (self->num != -1) { - // LWIP Socket - // TODO: deal with potential failure/add timeout? - sent = lwip_send(self->num, buf, len, 0); - } else if (self->tls != NULL) { - // TLS Socket - sent = esp_tls_conn_write(self->tls, buf, len); +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) { + + struct sockaddr_in source_addr; + socklen_t socklen = sizeof(source_addr); + + // LWIP Socket + uint64_t start_ticks = supervisor_ticks_ms64(); + 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 = supervisor_ticks_ms64() - start_ticks >= self->timeout_ms; + } + RUN_BACKGROUND_TASKS; + received = lwip_recvfrom(self->num, buf, len, 0, (struct sockaddr *)&source_addr, &socklen); + + // In non-blocking mode, fail instead of looping + if (received == -1 && self->timeout_ms == 0) { + mp_raise_OSError(MP_EAGAIN); + } } - if (sent < 0) { - mp_raise_OSError(MP_ENOTCONN); + if (!timed_out) { + memcpy((void *)ip, (void *)&source_addr.sin_addr.s_addr, sizeof(source_addr.sin_addr.s_addr)); + *port = htons(source_addr.sin_port); + } else { + mp_raise_OSError(ETIMEDOUT); } - return sent; + + if (received < 0) { + mp_raise_BrokenPipeError(); + return 0; + } + + return received; } -mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t* self, const uint8_t* buf, mp_uint_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; @@ -249,60 +251,20 @@ 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 - 1, 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) { mp_raise_OSError(MP_EAGAIN); } } - } else if (self->tls != NULL) { - // TLS Socket - int status = 0; - uint64_t start_ticks = supervisor_ticks_ms64(); - int sockfd; - esp_err_t err = esp_tls_get_conn_sockfd(self->tls, &sockfd); - if (err != ESP_OK) { - mp_raise_OSError(MP_EBADF); - } - while (received == 0 && - status >= 0 && - !timed_out && - !mp_hal_is_interrupted()) { - if (self->timeout_ms != (uint)-1) { - timed_out = self->timeout_ms == 0 || supervisor_ticks_ms64() - start_ticks >= self->timeout_ms; - } - RUN_BACKGROUND_TASKS; - size_t available = esp_tls_get_bytes_avail(self->tls); - if (available == 0) { - // This reads the raw socket buffer and is used for non-TLS connections - // and between encrypted TLS blocks. - status = lwip_ioctl(sockfd, FIONREAD, &available); - } - size_t remaining = len - received; - if (available > remaining) { - available = remaining; - } - if (available > 0) { - 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.) - break; - } - if (status > 0) { - received += status; - } - } - } } else { - // Socket does not have a valid descriptor of either type mp_raise_OSError(MP_EBADF); } @@ -312,29 +274,43 @@ mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t* self, return received; } -mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t* self, - const char* host, size_t hostlen, uint8_t port, const uint8_t* buf, mp_uint_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 + // TODO: deal with potential failure/add timeout? + sent = lwip_send(self->num, buf, len, 0); + } else { + mp_raise_OSError(MP_EBADF); + } + + if (sent < 0) { + mp_raise_OSError(errno); + } + return sent; +} - _lazy_init_LWIP(self); +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) { - // Get the IP address string + // Set parameters const struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM, }; - struct addrinfo *result; - int error = lwip_getaddrinfo(host, NULL, &hints, &result); - if (error != 0 || result == NULL) { - return 0; + struct addrinfo *result_i; + int error = lwip_getaddrinfo(host, NULL, &hints, &result_i); + if (error != 0 || result_i == NULL) { + mp_raise_OSError(EHOSTUNREACH); } // Set parameters struct sockaddr_in dest_addr; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" - dest_addr.sin_addr.s_addr = ((struct sockaddr_in *)result->ai_addr)->sin_addr.s_addr; + dest_addr.sin_addr.s_addr = ((struct sockaddr_in *)result_i->ai_addr)->sin_addr.s_addr; #pragma GCC diagnostic pop - freeaddrinfo(result); + freeaddrinfo(result_i); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(port); @@ -347,66 +323,6 @@ mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t* self, return bytes_sent; } -mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t* self, - uint8_t* buf, mp_uint_t len, uint8_t* ip, uint *port) { - - _lazy_init_LWIP(self); - - struct sockaddr_in source_addr; - socklen_t socklen = sizeof(source_addr); - - // LWIP Socket - uint64_t start_ticks = supervisor_ticks_ms64(); - 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 = supervisor_ticks_ms64() - start_ticks >= self->timeout_ms; - } - RUN_BACKGROUND_TASKS; - received = lwip_recvfrom(self->num, buf, len, 0, (struct sockaddr *)&source_addr, &socklen); - - // In non-blocking mode, fail instead of looping - if (received == -1 && self->timeout_ms == 0) { - mp_raise_OSError(MP_EAGAIN); - } - } - - if (!timed_out) { - 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); - } - - if (received < 0) { - mp_raise_BrokenPipeError(); - return 0; - } - - return received; -} - -void common_hal_socketpool_socket_close(socketpool_socket_obj_t* self) { - self->connected = false; - if (self->tls != NULL) { - esp_tls_conn_destroy(self->tls); - self->tls = NULL; - } - if (self->num >= 0) { - lwip_shutdown(self->num, 0); - lwip_close(self->num); - self->num = -1; - } -} - -bool common_hal_socketpool_socket_get_closed(socketpool_socket_obj_t* self) { - return self->tls == NULL && self->num < 0; -} - - -mp_uint_t common_hal_socketpool_socket_get_hash(socketpool_socket_obj_t* self) { - return self->num; +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 4e6cfa5ef628e..87f8b20dbb01b 100644 --- a/ports/esp32s2/common-hal/socketpool/Socket.h +++ b/ports/esp32s2/common-hal/socketpool/Socket.h @@ -41,13 +41,11 @@ typedef struct { int family; int ipproto; bool connected; - esp_tls_t* tls; - ssl_sslcontext_obj_t* ssl_context; - 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 70a8b4eca5069..4cea95ec41952 100644 --- a/ports/esp32s2/common-hal/socketpool/SocketPool.c +++ b/ports/esp32s2/common-hal/socketpool/SocketPool.c @@ -25,6 +25,7 @@ */ #include "shared-bindings/socketpool/SocketPool.h" +#include "common-hal/socketpool/Socket.h" #include "py/runtime.h" #include "shared-bindings/wifi/__init__.h" @@ -33,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; @@ -65,29 +66,29 @@ socketpool_socket_obj_t* common_hal_socketpool_socket(socketpool_socketpool_obj_ mp_raise_NotImplementedError(translate("Only IPv4 sockets supported")); } - // Consider LWIP and MbedTLS "variant" sockets to be incompatible (for now) - // The variant of the socket is determined by whether the socket is wrapped - // by SSL. If no TLS handle is set in sslcontext_wrap_socket, the first call - // of bind() or connect() will create a LWIP socket with a corresponding - // socketnum. - // TODO: move MbedTLS to its own duplicate Socket or Server API, maybe? socketpool_socket_obj_t *sock = m_new_obj_with_finaliser(socketpool_socket_obj_t); sock->base.type = &socketpool_socket_type; - sock->num = -1; sock->type = socket_type; sock->family = addr_family; sock->ipproto = ipproto; + sock->pool = self; sock->timeout_ms = (uint)-1; - sock->tls = NULL; - sock->ssl_context = NULL; - sock->pool = self; + // Create LWIP socket + int socknum = -1; + socknum = lwip_socket(sock->family, sock->type, sock->ipproto); + if (socknum < 0 || !register_open_socket(sock)) { + mp_raise_RuntimeError(translate("Out of sockets")); + } + sock->num = socknum; + // Sockets should be nonblocking in most cases + lwip_fcntl(socknum, F_SETFL, O_NONBLOCK); return sock; } -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 e24fd338b6de2..a94c1df1eb248 100644 --- a/ports/esp32s2/common-hal/ssl/SSLContext.c +++ b/ports/esp32s2/common-hal/ssl/SSLContext.c @@ -25,17 +25,36 @@ */ #include "shared-bindings/ssl/SSLContext.h" +#include "shared-bindings/ssl/SSLSocket.h" + +#include "bindings/espidf/__init__.h" #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) { } -socketpool_socket_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")); + } + + ssl_sslsocket_obj_t *sock = m_new_obj_with_finaliser(ssl_sslsocket_obj_t); + sock->base.type = &ssl_sslsocket_type; + sock->ssl_context = self; + sock->sock = socket; + + esp_tls_t *tls_handle = esp_tls_init(); + if (tls_handle == NULL) { + mp_raise_espidf_MemoryError(); + } + sock->tls = tls_handle; + + // TODO: do something with the original socket? Don't call a close on the internal LWIP. - socket->ssl_context = self; // Should we store server hostname on the socket in case connect is called with an ip? - return socket; + return sock; } diff --git a/ports/esp32s2/common-hal/ssl/SSLSocket.c b/ports/esp32s2/common-hal/ssl/SSLSocket.c new file mode 100644 index 0000000000000..724d2aac92c40 --- /dev/null +++ b/ports/esp32s2/common-hal/ssl/SSLSocket.c @@ -0,0 +1,176 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * Copyright (c) 2021 Lucian Copeland for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "shared-bindings/ssl/SSLSocket.h" +#include "shared-bindings/socketpool/Socket.h" +#include "shared-bindings/ssl/SSLContext.h" + +#include "bindings/espidf/__init__.h" +#include "lib/utils/interrupt_char.h" +#include "py/mperrno.h" +#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); + return sslsock; +} + +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) { + 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; + 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; + if (result < 0) { + int esp_tls_code; + int flags; + esp_err_t err = esp_tls_get_and_clear_last_error(self->tls->error_handle, &esp_tls_code, &flags); + + if (err == ESP_ERR_MBEDTLS_SSL_SETUP_FAILED) { + mp_raise_espidf_MemoryError(); + } else if (ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED) { + mp_raise_OSError_msg_varg(translate("Failed SSL handshake")); + } else { + mp_raise_OSError_msg_varg(translate("Unhandled ESP TLS error %d %d %x %d"), esp_tls_code, flags, err, result); + } + } else { + // Connection successful, set the timeout on the underlying socket. We can't rely on the IDF + // to do it because the config structure is only used for TLS connections. Generally, we + // shouldn't hit this timeout because we try to only read available data. However, there is + // always a chance that we try to read something that is used internally. + int fd; + esp_tls_get_conn_sockfd(self->tls, &fd); + struct timeval tv; + tv.tv_sec = 2 * 60; // Two minutes + tv.tv_usec = 0; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + } + + return self->sock->connected; +} + +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) { + return self->sock->connected; +} + +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) { + int received = 0; + bool timed_out = false; + int status = 0; + uint64_t start_ticks = supervisor_ticks_ms64(); + int sockfd; + esp_err_t err = esp_tls_get_conn_sockfd(self->tls, &sockfd); + if (err != ESP_OK) { + mp_raise_OSError(MP_EBADF); + } + while (received == 0 && + status >= 0 && + !timed_out && + !mp_hal_is_interrupted()) { + if (self->sock->timeout_ms != (uint)-1 && self->sock->timeout_ms != 0) { + timed_out = self->sock->timeout_ms == 0 || supervisor_ticks_ms64() - start_ticks >= self->sock->timeout_ms; + } + RUN_BACKGROUND_TASKS; + size_t available = esp_tls_get_bytes_avail(self->tls); + if (available == 0) { + // This reads the raw socket buffer and is used for non-TLS connections + // and between encrypted TLS blocks. + status = lwip_ioctl(sockfd, FIONREAD, &available); + } + size_t remaining = len - received; + if (available > remaining) { + available = remaining; + } + if (available > 0) { + 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.) + break; + } + if (status > 0) { + received += status; + } + } + // In non-blocking mode, fail instead of timing out + if (received == 0 && self->sock->timeout_ms == 0) { + mp_raise_OSError(MP_EAGAIN); + } + } + + if (timed_out) { + mp_raise_OSError(ETIMEDOUT); + } + return received; +} + +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); + + if (sent < 0) { + int esp_tls_code; + int flags; + esp_err_t err = esp_tls_get_and_clear_last_error(self->tls->error_handle, &esp_tls_code, &flags); + + if (err == ESP_ERR_MBEDTLS_SSL_SETUP_FAILED) { + mp_raise_espidf_MemoryError(); + } else if (ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED) { + mp_raise_OSError_msg_varg(translate("Failed SSL handshake")); + } else { + mp_raise_OSError_msg_varg(translate("Unhandled ESP TLS error %d %d %x %d"), esp_tls_code, flags, err, sent); + } + } + return sent; +} + +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 new file mode 100644 index 0000000000000..b485781259a0f --- /dev/null +++ b/ports/esp32s2/common-hal/ssl/SSLSocket.h @@ -0,0 +1,44 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Lucian Copeland for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_ESP32S2_COMMON_HAL_SSL_SSLSOCKET_H +#define MICROPY_INCLUDED_ESP32S2_COMMON_HAL_SSL_SSLSOCKET_H + +#include "py/obj.h" + +#include "common-hal/ssl/SSLContext.h" +#include "common-hal/socketpool/Socket.h" + +#include "components/esp-tls/esp_tls.h" + +typedef struct { + mp_obj_base_t base; + 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 8d386d0c3a245..a0886adda7194 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 ea663f897d54a..f827651781f10 100644 --- a/ports/esp32s2/common-hal/supervisor/Runtime.c +++ b/ports/esp32s2/common-hal/supervisor/Runtime.c @@ -28,10 +28,10 @@ #include "shared-bindings/supervisor/Runtime.h" #include "supervisor/serial.h" -bool common_hal_get_serial_connected(void) { - return (bool) serial_connected(); +bool common_hal_supervisor_runtime_get_serial_connected(void) { + return (bool)serial_connected(); } -bool common_hal_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); +bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { + return (bool)serial_bytes_available(); } diff --git a/ports/esp32s2/common-hal/touchio/TouchIn.c b/ports/esp32s2/common-hal/touchio/TouchIn.c index 401b84d5c2d40..53bc335d30d05 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 2f7c66d2b855f..d4ce2d8a5f850 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 b51a391b7f3b5..f17a037ff478e 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) { @@ -49,13 +49,13 @@ void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { } void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self) { - if (esp_task_wdt_deinit() == ESP_OK) { + if (esp_task_wdt_delete(NULL) == ESP_OK && esp_task_wdt_deinit() == ESP_OK) { self->mode = WATCHDOGMODE_NONE; } } 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 04d9aeee6c29c..c26d140139dc2 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 b6eb6bb433e95..49507df0d5d34 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 574bab0a1912f..9c8ccaf7f24a1 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 cc733308db60e..62ef62b7f5631 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 36da387f212f6..9790c4ab331ab 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 b8e8f731bd812..3ec4ebc24df90 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,8 +107,9 @@ 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; // Even though we just called esp_netif_create_default_wifi_sta, // station mode isn't actually ready for use until esp_wifi_set_mode() @@ -119,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); @@ -143,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 d2bd06c570cda..1dbe50a04b571 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-idf b/ports/esp32s2/esp-idf index ebe7784258d8c..f30a865fd1a44 160000 --- a/ports/esp32s2/esp-idf +++ b/ports/esp32s2/esp-idf @@ -1 +1 @@ -Subproject commit ebe7784258d8c10e9cc334ccc00c3fd270746c8b +Subproject commit f30a865fd1a44d880b909b84112f74741412c2ce diff --git a/ports/esp32s2/esp_error.c b/ports/esp32s2/esp_error.c index 57bc51528d5e4..4bc44674b7fba 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 8bdc047c12091..631f7f0982486 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 0cf695bc9807c..a3db0ab3d5e38 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/mpconfigport.mk b/ports/esp32s2/mpconfigport.mk index 562c60998c29e..5073d8812dd8c 100644 --- a/ports/esp32s2/mpconfigport.mk +++ b/ports/esp32s2/mpconfigport.mk @@ -28,18 +28,18 @@ CIRCUITPY_FREQUENCYIO = 1 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_ROTARYIO = 1 CIRCUITPY_NVM = 1 +CIRCUITPY_PS2IO ?= 1 +CIRCUITPY_TOUCHIO_USE_NATIVE ?= 1 # We don't have enough endpoints to include MIDI. -CIRCUITPY_USB_MIDI = 0 +CIRCUITPY_USB_MIDI ?= 0 +CIRCUITPY_USB_HID ?= 1 +# We have borrowed the VENDOR nomenclature from tinyusb. VENDOR AKA WEBUSB +CIRCUITPY_USB_VENDOR ?= 0 CIRCUITPY_WIFI = 1 CIRCUITPY_WATCHDOG ?= 1 -CIRCUITPY_ESPIDF = 1 - -ifndef CIRCUITPY_PS2IO -CIRCUITPY_PS2IO = 1 -endif -ifndef CIRCUITPY_TOUCHIO_USE_NATIVE -CIRCUITPY_TOUCHIO_USE_NATIVE = 1 -endif +CIRCUITPY_ESPIDF = 1 CIRCUITPY_MODULE ?= none + +USB_NUM_EP = 5 diff --git a/ports/esp32s2/mphalport.c b/ports/esp32s2/mphalport.c index 9b4c4bc5ebd63..aaf1f468ffd96 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 4feddbd9b0ce3..8682baec458db 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 dd24569bef933..e4578a279124a 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 4fce13f4d6cac..8bd8b0272bfa3 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 0d3d89ad50c3c..f882281405e8d --- 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 e0f5e7ddfe4a9..c92f4b4ccedf0 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 0ae1403874ff9..674d7fc5b2154 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 8c9ebd91c9c91..54150069c4cae 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 de69a49f9462e..8f3d9177655b3 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 534f7f71bfcfc..d48b7ef8927b8 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 16657d4079de9..54ac88dc44dbe 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 3f078895af6db..523677baea0de 100644 --- a/ports/esp32s2/tools/decode_backtrace.py +++ b/ports/esp32s2/tools/decode_backtrace.py @@ -15,9 +15,10 @@ 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/Makefile b/ports/litex/Makefile index f384f24577bc2..9f0d807469caf 100644 --- a/ports/litex/Makefile +++ b/ports/litex/Makefile @@ -136,7 +136,7 @@ SRC_C += \ lib/utils/sys_stdio_mphal.c \ supervisor/shared/memory.c -ifneq ($(USB),FALSE) +ifneq ($(CIRCUITPY_USB),0) SRC_C += lib/tinyusb/src/portable/valentyusb/eptri/dcd_eptri.c endif diff --git a/ports/litex/background.c b/ports/litex/background.c index 174d9588ac660..da86919c0cfec 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 bf66fe3a17b4b..7405d431251bf 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 91b2f1a310a33..1d73bbf0ff26f 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 127301eee2b0c..fd627c0b057ff 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 6be495c3319ad..804a8b37f9913 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 53df637c438a2..96cc95dfa6be6 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 4d088a0763806..1cc4c41d58a79 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 29fd318d401e7..e7e5600fb1ed2 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 578f3e8c63c27..c070c2777e930 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 ea663f897d54a..f827651781f10 100644 --- a/ports/litex/common-hal/supervisor/Runtime.c +++ b/ports/litex/common-hal/supervisor/Runtime.c @@ -28,10 +28,10 @@ #include "shared-bindings/supervisor/Runtime.h" #include "supervisor/serial.h" -bool common_hal_get_serial_connected(void) { - return (bool) serial_connected(); +bool common_hal_supervisor_runtime_get_serial_connected(void) { + return (bool)serial_connected(); } -bool common_hal_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); +bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { + return (bool)serial_bytes_available(); } diff --git a/ports/litex/fatfs_port.c b/ports/litex/fatfs_port.c index 8bdc047c12091..631f7f0982486 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 b902bc4f27530..8b3a0304ee677 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 dc96c228d8779..34c8b0a10a0ae 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)); }) - -static inline unsigned int irq_getie(void) -{ - return (csrr(mstatus) & CSR_MSTATUS_MIE) != 0; + 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 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 5f739e49ead60..cedc3badc3058 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/mpconfigport.mk b/ports/litex/mpconfigport.mk index 003fb5c2c3718..af6a94e64adc5 100644 --- a/ports/litex/mpconfigport.mk +++ b/ports/litex/mpconfigport.mk @@ -6,6 +6,9 @@ MPY_TOOL_LONGINT_IMPL = -mlongint-impl=mpz # Internal math library is substantially smaller than toolchain one INTERNAL_LIBM = 1 +# Number of USB endpoint pairs. +USB_NUM_EP = 16 + # Chip supplied serial number, in bytes USB_SERIAL_NUMBER_LENGTH = 30 diff --git a/ports/litex/mphalport.c b/ports/litex/mphalport.c index c7369dc0507c5..5eedc73f3c736 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 540575c5879ee..62c8e0bab3a76 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 9b1dea685217e..5c58c7bc499cb 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,9 +308,9 @@ 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 + #if CIRCUITPY_USB usb_background(); #endif @@ -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,11 +343,11 @@ 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 + #if CIRCUITPY_USB usb_background(); #endif } diff --git a/ports/litex/supervisor/port.c b/ports/litex/supervisor/port.c index 04ff1c09bf131..6f108ee051794 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/Makefile b/ports/mimxrt10xx/Makefile index 04949bf01c2d4..33507086eaa23 100644 --- a/ports/mimxrt10xx/Makefile +++ b/ports/mimxrt10xx/Makefile @@ -146,6 +146,7 @@ SRC_SDK := \ system_$(CHIP_FAMILY).c \ SRC_SDK := $(addprefix sdk/devices/$(CHIP_FAMILY)/, $(SRC_SDK)) +$(addprefix $(BUILD)/, $(SRC_SDK:.c=.o)): CFLAGS += -Wno-undef SRC_C += \ background.c \ diff --git a/ports/mimxrt10xx/background.c b/ports/mimxrt10xx/background.c index a8a613d41a42b..9e531cea23e49 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 1db1dd68614e6..5e20e5e3c291d 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 9ba3e168f504a..5871dda963ea6 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, + + .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 = { - .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. - - .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 - }, + // 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 1db1dd68614e6..5e20e5e3c291d 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 eafc9ac3af1fd..7460615c4c9ab 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, + + .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 = { - .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. - - .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 - }, + // 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 4e5de8de276a4..b752b8ed30715 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 26f55f96e1354..3782d3f2d287c 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 fef1c11e3e482..d6cfc07e627d7 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, + + .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 = { - .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. - - .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 - }, + // 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 4c3953187e58a..7b335d896cfb2 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 8519893a5f73f..9f7a22a86ffe4 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 00ee47c98530c..9c88f689d8e4b 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, + + .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 = { - .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. - - .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 - }, + // 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/imxrt1010_evk/mpconfigboard.mk b/ports/mimxrt10xx/boards/imxrt1010_evk/mpconfigboard.mk index 81eb63597326b..09161ece32624 100644 --- a/ports/mimxrt10xx/boards/imxrt1010_evk/mpconfigboard.mk +++ b/ports/mimxrt10xx/boards/imxrt1010_evk/mpconfigboard.mk @@ -6,3 +6,7 @@ USB_MANUFACTURER = "NXP" CHIP_VARIANT = MIMXRT1011DAE5A CHIP_FAMILY = MIMXRT1011 FLASH = AT25SF128A + +# Include these Python libraries in the firmware +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ESP32SPI +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Requests diff --git a/ports/mimxrt10xx/boards/imxrt1010_evk/pins.c b/ports/mimxrt10xx/boards/imxrt1010_evk/pins.c index 4aad9aaeb3324..dac4fc0d6e3df 100644 --- a/ports/mimxrt10xx/boards/imxrt1010_evk/pins.c +++ b/ports/mimxrt10xx/boards/imxrt1010_evk/pins.c @@ -7,12 +7,9 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO_10) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO_AD_05) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO_AD_06) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO_08) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO_01) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO_AD_01) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO_AD_02) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO_SD_02) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO_03) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO_AD_05) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO_AD_04) }, { MP_OBJ_NEW_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO_AD_03) }, diff --git a/ports/mimxrt10xx/boards/imxrt1020_evk/board.c b/ports/mimxrt10xx/boards/imxrt1020_evk/board.c index 531c0c6f62e31..4ae1e19b0d5f1 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 4c3ba471797ec..6589ad9c4875a 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, + + .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 = { - .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. - - .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 - }, + // 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 e7d74ab49f73b..c4a2867ab1717 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 502e21a3b09bb..40db33444fb01 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, + + .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 = { - .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. - - .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 - }, + // 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 1db1dd68614e6..5e20e5e3c291d 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 991bc43e45c32..b2894d766962b 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. +// Config for W25Q32JV with QSPI routed. (compatible with GD25Q32) __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, + + .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 = { - .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. - - .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 - }, + // 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/metro_m7_1011/mpconfigboard.h b/ports/mimxrt10xx/boards/metro_m7_1011/mpconfigboard.h index b11edb18b42cb..23009f353fa77 100644 --- a/ports/mimxrt10xx/boards/metro_m7_1011/mpconfigboard.h +++ b/ports/mimxrt10xx/boards/metro_m7_1011/mpconfigboard.h @@ -7,7 +7,7 @@ // make sure you don't overwrite code #define CIRCUITPY_INTERNAL_NVM_SIZE 0 -#define BOARD_FLASH_SIZE (2 * 1024 * 1024) +#define BOARD_FLASH_SIZE (4 * 1024 * 1024) #define DEFAULT_I2C_BUS_SCL (&pin_GPIO_02) #define DEFAULT_I2C_BUS_SDA (&pin_GPIO_01) diff --git a/ports/mimxrt10xx/boards/metro_m7_1011/mpconfigboard.mk b/ports/mimxrt10xx/boards/metro_m7_1011/mpconfigboard.mk index 1a3f7e766c0b8..2655217c7880d 100644 --- a/ports/mimxrt10xx/boards/metro_m7_1011/mpconfigboard.mk +++ b/ports/mimxrt10xx/boards/metro_m7_1011/mpconfigboard.mk @@ -1,11 +1,11 @@ USB_VID = 0x239A USB_PID = 0x80E2 -USB_PRODUCT = "Metro M7 1011" +USB_PRODUCT = "Metro M7 iMX RT1011" USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = MIMXRT1011DAE5A CHIP_FAMILY = MIMXRT1011 -FLASH = W25Q16JV +FLASH = W25Q32JV # Include these Python libraries in the firmware FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ESP32SPI diff --git a/ports/mimxrt10xx/boards/metro_m7_1011/pins.c b/ports/mimxrt10xx/boards/metro_m7_1011/pins.c index ea9ae55290a16..f79dd21e9c1d0 100644 --- a/ports/mimxrt10xx/boards/metro_m7_1011/pins.c +++ b/ports/mimxrt10xx/boards/metro_m7_1011/pins.c @@ -42,10 +42,6 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO_AD_03) }, { MP_OBJ_NEW_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO_AD_04) }, - // UART - { MP_OBJ_NEW_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO_10) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO_09) }, - // I2C { MP_OBJ_NEW_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO_01) }, { MP_OBJ_NEW_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO_02) }, diff --git a/ports/mimxrt10xx/boards/teensy40/flash_config.c b/ports/mimxrt10xx/boards/teensy40/flash_config.c index 991bc43e45c32..3f4ab0271d991 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, + + .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 = { - .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. - - .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 - }, + // 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/mpconfigboard.mk b/ports/mimxrt10xx/boards/teensy40/mpconfigboard.mk index 7900d327ae0e6..3a732454037a3 100644 --- a/ports/mimxrt10xx/boards/teensy40/mpconfigboard.mk +++ b/ports/mimxrt10xx/boards/teensy40/mpconfigboard.mk @@ -6,3 +6,4 @@ USB_MANUFACTURER = "PJRC" CHIP_VARIANT = MIMXRT1062DVJ6A CHIP_FAMILY = MIMXRT1062 FLASH = W25Q16JV +CIRCUITPY__EVE = 1 diff --git a/ports/mimxrt10xx/boards/teensy41/flash_config.c b/ports/mimxrt10xx/boards/teensy41/flash_config.c index c0e0c86f98d90..09886dece6e15 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, + + .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 = { - .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. - - .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 - }, + // 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/teensy41/mpconfigboard.mk b/ports/mimxrt10xx/boards/teensy41/mpconfigboard.mk index 201e0e660f75b..035c51b553997 100644 --- a/ports/mimxrt10xx/boards/teensy41/mpconfigboard.mk +++ b/ports/mimxrt10xx/boards/teensy41/mpconfigboard.mk @@ -6,3 +6,4 @@ USB_MANUFACTURER = "PJRC" CHIP_VARIANT = MIMXRT1062DVJ6A CHIP_FAMILY = MIMXRT1062 FLASH = W25Q64JV +CIRCUITPY__EVE = 1 diff --git a/ports/mimxrt10xx/common-hal/analogio/AnalogIn.c b/ports/mimxrt10xx/common-hal/analogio/AnalogIn.c index 9587eba633d93..5e7bb82c77719 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 6bdbeff7c22d1..bf21e30df3a22 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 aaa2549a816a4..74639d0ef169e 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,10 +106,10 @@ 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("SDA or SCL needs a pull up")); + mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); } #endif @@ -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 ce7cbea7ecd9d..88923fe06da7a 100644 --- a/ports/mimxrt10xx/common-hal/busio/SPI.c +++ b/ports/mimxrt10xx/common-hal/busio/SPI.c @@ -38,7 +38,9 @@ #define LPSPI_MASTER_CLK_FREQ (CLOCK_GetFreq(kCLOCK_Usb1PllPfd0Clk) / (CLOCK_GetDiv(kCLOCK_LpspiDiv) + 1)) -//arrays use 0 based numbering: SPI1 is stored at index 0 +#define MAX_SPI_BUSY_RETRIES 100 + +// 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]; @@ -53,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) { @@ -72,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); @@ -84,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; } @@ -101,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]; @@ -114,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; } @@ -132,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; } @@ -151,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")); } } @@ -185,6 +187,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, LPSPI_Enable(self->spi, false); uint32_t tcrPrescaleValue; self->baudrate = LPSPI_MasterSetBaudRate(self->spi, config.baudRate, LPSPI_MASTER_CLK_FREQ, &tcrPrescaleValue); + self->spi->TCR = (self->spi->TCR & ~LPSPI_TCR_PRESCALE_MASK) | LPSPI_TCR_PRESCALE(tcrPrescaleValue); LPSPI_Enable(self->spi, true); claim_pin(self->clock->pin); @@ -229,16 +232,16 @@ 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; - self->baudrate = LPSPI_MasterSetBaudRate(self->spi, baudrate, LPSPI_MASTER_CLK_FREQ, &tcrPrescaleValue); - LPSPI_Enable(self->spi, true); + if (baudrate > 30000000) { + baudrate = 30000000; // "Absolute maximum frequency of operation (fop) is 30 MHz" -- IMXRT1010CEC.pdf + } if ((polarity == common_hal_busio_spi_get_polarity(self)) && (phase == common_hal_busio_spi_get_phase(self)) && - (bits == ((self->spi->TCR & LPSPI_TCR_FRAMESZ_MASK) >> LPSPI_TCR_FRAMESZ_SHIFT)) + 1) { + (bits == ((self->spi->TCR & LPSPI_TCR_FRAMESZ_MASK) >> LPSPI_TCR_FRAMESZ_SHIFT)) + 1 && + (baudrate == common_hal_busio_spi_get_frequency(self))) { return true; } @@ -249,10 +252,22 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, config.cpol = polarity; config.cpha = phase; config.bitsPerFrame = bits; + // The between-transfer-delay must be equal to the SCK low-time. + // Setting it lower introduces runt pulses, while setting it higher + // wastes time. + config.betweenTransferDelayInNanoSec = (1000000000 / config.baudRate) / 2; LPSPI_Deinit(self->spi); LPSPI_MasterInit(self->spi, &config, LPSPI_MASTER_CLK_FREQ); + // Recompute the actual baudrate so that we can set the baudrate + // (frequency) property. We don't need to set TCR because it was + // established by LPSPI_MasterInit, above + uint32_t tcrPrescaleValue; + LPSPI_Enable(self->spi, false); + self->baudrate = LPSPI_MasterSetBaudRate(self->spi, baudrate, LPSPI_MASTER_CLK_FREQ, &tcrPrescaleValue); + LPSPI_Enable(self->spi, true); + return true; } @@ -275,8 +290,23 @@ void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { self->has_lock = false; } +static status_t transfer_common(busio_spi_obj_t *self, lpspi_transfer_t *xfer) { + xfer->configFlags = kLPSPI_MasterPcsContinuous; + + status_t status; + int retries = MAX_SPI_BUSY_RETRIES; + do { + status = LPSPI_MasterTransferBlocking(self->spi, xfer); + } while (status == kStatus_LPSPI_Busy && --retries > 0); + + if (status != kStatus_Success) { + printf("%s: status %ld\r\n", __func__, status); + } + return status; +} + 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; } @@ -285,19 +315,16 @@ 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; - const status_t status = LPSPI_MasterTransferBlocking(self->spi, &xfer); - if (status != kStatus_Success) - printf("%s: status %ld\r\n", __func__, status); + status_t status = transfer_common(self, &xfer); - 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; } @@ -311,11 +338,9 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, xfer.rxData = data; xfer.dataSize = len; - const status_t status = LPSPI_MasterTransferBlocking(self->spi, &xfer); - if (status != kStatus_Success) - printf("%s: status %ld\r\n", __func__, status); + status_t status = transfer_common(self, &xfer); - 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) { @@ -333,21 +358,19 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou xfer.rxData = data_in; xfer.dataSize = len; - const status_t status = LPSPI_MasterTransferBlocking(self->spi, &xfer); - if (status != kStatus_Success) - printf("%s: status %ld\r\n", __func__, status); + status_t status = transfer_common(self, &xfer); - 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 03a6e8f3efb14..ec0296156ad2c 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,24 +74,28 @@ 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; self->timeout_ms = timeout * 1000; + if (self->character_bits != 7 && self->character_bits != 8) { + mp_raise_ValueError(translate("Invalid word/bit length")); + } + // We are transmitting one direction if one pin is NULL and the other isn't. bool is_onedirection = (rx == NULL) != (tx == NULL); bool uart_taken = false; @@ -150,12 +153,15 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_raise_ValueError(translate("Supply at least one UART pin")); } - if (uart_taken) { - mp_raise_ValueError(translate("Hardware in use, try alternative pins")); + if (rx && !self->rx) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_RX); + } + if (tx && !self->tx) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_TX); } - if(self->rx == NULL && self->tx == NULL) { - mp_raise_ValueError(translate("Invalid pins")); + if (uart_taken) { + mp_raise_ValueError(translate("Hardware in use, try alternative pins")); } if (is_onedirection && ((rts != NULL) || (cts != NULL))) { @@ -169,8 +175,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 +186,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 +194,13 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } } } - if (self->rts == NULL){ - mp_raise_ValueError(translate("Selected RTS pin not valid")); + if (self->rts == NULL) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_RTS); } } 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,17 +208,20 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } } } - if (self->cts == NULL){ - mp_raise_ValueError(translate("Selected CTS pin not valid")); + if (self->cts == NULL) { + mp_raise_ValueError_varg(translate("Invalid %q pin"), MP_QSTR_CTS); } } if (self->rx) { self->uart = mcu_uart_banks[self->rx->bank_idx - 1]; } else { + assert(self->tx); self->uart = mcu_uart_banks[self->tx->bank_idx - 1]; } + assert(self->uart); + if (self->rx) { config_periph_pin(self->rx); } @@ -326,7 +334,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 +380,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 94a5fb02c0c8a..604fef2cf31cc 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 e4eda9f4ffc40..445ffa91c5e04 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 0fdf4413b69d6..f7889c70f4df5 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, uint32_t frequency) { 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 50970f8e22509..b55ab6e862b70 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 2f1aaa89553aa..fde7fc8b8f110 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 efbde35d28136..b097133d5791c 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 6a8537e2da17b..3f638dc039a4a 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" @@ -39,6 +39,8 @@ #include "supervisor/shared/safe_mode.h" #include "supervisor/shared/translate.h" +#define DBL_TAP_REG SNVS->LPGPR[3] + void common_hal_mcu_delay_us(uint32_t delay) { mp_hal_delay_us(delay); } @@ -72,10 +74,10 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { } // Pretend to be the first of the two reset presses needed to enter the // bootloader. That way one reset will end in the bootloader. - SNVS->LPGPR[0] = DBL_TAP_MAGIC; + DBL_TAP_REG = DBL_TAP_MAGIC; } else { // Set up the default. - SNVS->LPGPR[0] = DBL_TAP_MAGIC_QUICK_BOOT; + DBL_TAP_REG = DBL_TAP_MAGIC_QUICK_BOOT; } if (runmode == RUNMODE_SAFE_MODE) { safe_mode_on_next_reset(PROGRAMMATIC_SAFE_MODE); @@ -102,14 +104,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 +127,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 +156,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 +286,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 b86077015c0f5..88d0453065368 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 e84beb526c741..dd1d186f1c5b6 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 cea11a4b9a266..c1f7ce20b62e0 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 af742f319f5e1..cce4f58ca71f7 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 d3a1a897ff3cb..b38f6f093fcbf 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 ee70ac17ec940..da022b738dc06 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 dd464ef846ac2..458fee641210e 100644 --- a/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +++ b/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -31,38 +31,54 @@ #include "py/runtime.h" #include "common-hal/pwmio/PWMOut.h" #include "shared-bindings/pwmio/PWMOut.h" -#include "shared-bindings/microcontroller/Processor.h" +#include "shared-bindings/microcontroller/Pin.h" #include "fsl_pwm.h" #include "supervisor/shared/translate.h" #include "periph.h" -#include - +static void config_periph_pin(const mcu_pwm_obj_t *periph) { + IOMUXC_SetPinMux( + periph->pin->mux_reg, periph->mux_mode, + periph->input_reg, periph->input_idx, + periph->pin->cfg_reg, + 0); + + 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)); +} // 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,35 +135,49 @@ 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) +static int calculate_pulse_count(uint32_t frequency, uint8_t *prescaler) { + if (frequency > PWM_SRC_CLK_FREQ/2) { + return 0; + } + for(int shift = 0; shift<8; shift++) { + int pulse_count = PWM_SRC_CLK_FREQ/(1<= 65535) { + continue; + } + *prescaler = shift; + return pulse_count; + } + return 0; +} + 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); + } self->pwm = &mcu_pwm_list[i]; @@ -158,24 +188,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_INVALID_PIN; } - 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 -// 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 */ -// -// IOMUXC_SetPinConfig( -// IOMUXC_GPIO_SD_02_FLEXPWM1_PWM0_A, /* GPIO_02 PAD functional properties : */ -// 0x10A0U); /* Slew Rate Field: Slow Slew Rate -// Drive Strength Field: R0/4 -// Speed Field: fast(150MHz) -// Open Drain Enable Field: Open Drain Disabled -// Pull / Keep Enable Field: Pull/Keeper Enabled -// Pull / Keep Select Field: Keeper -// Pull Up / Down Config. Field: 100K Ohm Pull Down -// Hyst. Enable Field: Hysteresis Disabled */ + config_periph_pin(self->pwm); pwm_config_t pwmConfig; @@ -195,357 +208,120 @@ 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) { - printf("PWM initialization failed\r\n"); - return PWMOUT_INVALID_PIN; + self->pulse_count = calculate_pulse_count(frequency, &self->prescaler); + + if (self->pulse_count == 0) { + return PWMOUT_INVALID_FREQUENCY; } - pwm_signal_param_t pwmSignal; + pwmConfig.prescale = self->prescaler; - /* Set deadtime count, we set this to about 650ns */ - uint16_t deadTimeVal = ((uint64_t)PWM_SRC_CLK_FREQ * 650) / 1000000000; + if (PWM_Init(self->pwm->pwm, self->pwm->submodule, &pwmConfig) == kStatus_Fail) { + return PWMOUT_INVALID_PIN; + } - pwmSignal.pwmChannel = self->pwm->channel; - pwmSignal.level = kPWM_HighTrue; - pwmSignal.dutyCyclePercent = frequency / 2; /* 1 percent dutycycle */ - pwmSignal.deadtimeValue = deadTimeVal; + pwm_signal_param_t pwmSignal = { + .pwmChannel = self->pwm->channel, + .level = kPWM_HighTrue, + .dutyCyclePercent = 0, // avoid an initial transient + .deadtimeValue = 0, // allow 100% duty cycle + }; - PWM_SetupPwm(PWM1, self->pwm->submodule, &pwmSignal, 1, kPWM_SignedCenterAligned, frequency, PWM_SRC_CLK_FREQ); + // Disable all fault inputs + self->pwm->pwm->SM[self->pwm->submodule].DISMAP[0] = 0; + self->pwm->pwm->SM[self->pwm->submodule].DISMAP[1] = 0; - PWM_SetPwmLdok(PWM1, kPWM_Control_Module_0 | kPWM_Control_Module_1 | kPWM_Control_Module_2, true); + status_t status = PWM_SetupPwm(self->pwm->pwm, self->pwm->submodule, &pwmSignal, 1, kPWM_EdgeAligned, frequency, PWM_SRC_CLK_FREQ); - PWM_StartTimer(PWM1, kPWM_Control_Module_0 | kPWM_Control_Module_1 | kPWM_Control_Module_2); + if (status != kStatus_Success) { + return PWMOUT_INITIALIZATION_ERROR; + } + PWM_SetPwmLdok(self->pwm->pwm, 1 << self->pwm->submodule, true); -// if (frequency == 0 || frequency > 6000000) { -// return PWMOUT_INVALID_FREQUENCY; -// } + PWM_StartTimer(self->pwm->pwm, 1 << self->pwm->submodule); -// // Figure out which timer we are using. -// // First see if a tcc is already going with the frequency we want and our -// // channel is unused. tc's don't have enough channels to share. -// const pin_timer_t* timer = NULL; -// uint8_t mux_position = 0; -// if (!variable_frequency) { -// for (uint8_t i = 0; i < TCC_INST_NUM && timer == NULL; i++) { -// if (target_tcc_frequencies[i] != frequency) { -// continue; -// } -// for (uint8_t j = 0; j < NUM_TIMERS_PER_PIN && timer == NULL; j++) { -// const pin_timer_t* t = &pin->timer[j]; -// if (t->index != i || t->is_tc || t->index >= TCC_INST_NUM) { -// continue; -// } -// Tcc* tcc = tcc_insts[t->index]; -// if (tcc->CTRLA.bit.ENABLE == 1 && channel_ok(t)) { -// timer = t; -// mux_position = j; -// // Claim channel. -// tcc_channels[timer->index] |= (1 << tcc_channel(timer)); -// -// } -// } -// } -// } -// -// // No existing timer has been found, so find a new one to use and set it up. -// if (timer == NULL) { -// // By default, with fixed frequency we want to share a TCC because its likely we'll have -// // other outputs at the same frequency. If the frequency is variable then we'll only have -// // one output so we start with the TCs to see if they work. -// int8_t direction = -1; -// uint8_t start = NUM_TIMERS_PER_PIN - 1; -// bool found = false; -// if (variable_frequency) { -// direction = 1; -// start = 0; -// } -// for (int8_t i = start; i >= 0 && i < NUM_TIMERS_PER_PIN && timer == NULL; i += direction) { -// const pin_timer_t* t = &pin->timer[i]; -// if ((!t->is_tc && t->index >= TCC_INST_NUM) || -// (t->is_tc && t->index >= TC_INST_NUM)) { -// continue; -// } -// if (t->is_tc) { -// found = true; -// Tc* tc = tc_insts[t->index]; -// if (tc->COUNT16.CTRLA.bit.ENABLE == 0 && t->wave_output == 1) { -// timer = t; -// mux_position = i; -// } -// } else { -// Tcc* tcc = tcc_insts[t->index]; -// if (tcc->CTRLA.bit.ENABLE == 0 && channel_ok(t)) { -// timer = t; -// mux_position = i; -// } -// } -// } -// -// if (timer == NULL) { -// if (found) { -// return PWMOUT_ALL_TIMERS_ON_PIN_IN_USE; -// } -// return PWMOUT_ALL_TIMERS_IN_USE; -// } -// -// uint8_t resolution = 0; -// if (timer->is_tc) { -// resolution = 16; -// } else { -// // TCC resolution varies so look it up. -// const uint8_t _tcc_sizes[TCC_INST_NUM] = TCC_SIZES; -// resolution = _tcc_sizes[timer->index]; -// } -// // First determine the divisor that gets us the highest resolution. -// uint32_t system_clock = common_hal_mcu_processor_get_frequency(); -// uint32_t top; -// uint8_t divisor; -// for (divisor = 0; divisor < 8; divisor++) { -// top = (system_clock / prescaler[divisor] / frequency) - 1; -// if (top < (1u << resolution)) { -// break; -// } -// } -// -// set_timer_handler(timer->is_tc, timer->index, TC_HANDLER_NO_INTERRUPT); -// // We use the zeroeth clock on either port to go full speed. -// turn_on_clocks(timer->is_tc, timer->index, 0); -// -// if (timer->is_tc) { -// tc_periods[timer->index] = top; -// Tc* tc = tc_insts[timer->index]; -// #ifdef SAMD21 -// tc->COUNT16.CTRLA.reg = TC_CTRLA_MODE_COUNT16 | -// TC_CTRLA_PRESCALER(divisor) | -// TC_CTRLA_WAVEGEN_MPWM; -// tc->COUNT16.CC[0].reg = top; -// #endif -// #ifdef SAMD51 -// -// tc->COUNT16.CTRLA.bit.SWRST = 1; -// while (tc->COUNT16.CTRLA.bit.SWRST == 1) { -// } -// tc_set_enable(tc, false); -// tc->COUNT16.CTRLA.reg = TC_CTRLA_MODE_COUNT16 | TC_CTRLA_PRESCALER(divisor); -// tc->COUNT16.WAVE.reg = TC_WAVE_WAVEGEN_MPWM; -// tc->COUNT16.CCBUF[0].reg = top; -// tc->COUNT16.CCBUF[1].reg = 0; -// #endif -// -// tc_set_enable(tc, true); -// } else { -// tcc_periods[timer->index] = top; -// Tcc* tcc = tcc_insts[timer->index]; -// tcc_set_enable(tcc, false); -// tcc->CTRLA.bit.PRESCALER = divisor; -// tcc->PER.bit.PER = top; -// tcc->WAVE.bit.WAVEGEN = TCC_WAVE_WAVEGEN_NPWM_Val; -// tcc_set_enable(tcc, true); -// target_tcc_frequencies[timer->index] = frequency; -// tcc_refcount[timer->index]++; -// if (variable_frequency) { -// // We're changing frequency so claim all of the channels. -// tcc_channels[timer->index] = 0xff; -// } else { -// tcc_channels[timer->index] |= (1 << tcc_channel(timer)); -// } -// } -// } -// -// self->timer = timer; -// -// gpio_set_pin_function(pin->number, GPIO_PIN_FUNCTION_E + mux_position); common_hal_pwmio_pwmout_set_duty_cycle(self, duty); 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; } -// const pin_timer_t* t = self->timer; -// if (t->is_tc) { -// Tc* tc = tc_insts[t->index]; -// tc_set_enable(tc, false); -// tc->COUNT16.CTRLA.bit.SWRST = true; -// tc_wait_for_sync(tc); -// } else { -// tcc_refcount[t->index]--; -// tcc_channels[t->index] &= ~(1 << tcc_channel(t)); -// if (tcc_refcount[t->index] == 0) { -// target_tcc_frequencies[t->index] = 0; -// Tcc* tcc = tcc_insts[t->index]; -// tcc_set_enable(tcc, false); -// tcc->CTRLA.bit.SWRST = true; -// while (tcc->SYNCBUSY.bit.SWRST != 0) { -// /* Wait for sync */ -// } -// } -// } -// reset_pin_number(self->pin->number); + common_hal_reset_pin(self->pin); self->pin = NULL; } void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { - PWM_UpdatePwmDutycycle(PWM1, self->pwm->submodule, self->pwm->channel, kPWM_SignedCenterAligned, duty); - -// const pin_timer_t* t = self->timer; -// if (t->is_tc) { -// uint16_t adjusted_duty = tc_periods[t->index] * duty / 0xffff; -// #ifdef SAMD21 -// tc_insts[t->index]->COUNT16.CC[t->wave_output].reg = adjusted_duty; -// #endif -// #ifdef SAMD51 -// Tc* tc = tc_insts[t->index]; -// while (tc->COUNT16.SYNCBUSY.bit.CC1 != 0) {} -// tc->COUNT16.CCBUF[1].reg = adjusted_duty; -// #endif -// } else { -// uint32_t adjusted_duty = ((uint64_t) tcc_periods[t->index]) * duty / 0xffff; -// uint8_t channel = tcc_channel(t); -// Tcc* tcc = tcc_insts[t->index]; -// -// // Write into the CC buffer register, which will be transferred to the -// // CC register on an UPDATE (when period is finished). -// // Do clock domain syncing as necessary. -// -// while (tcc->SYNCBUSY.reg != 0) {} -// -// // Lock out double-buffering while updating the CCB value. -// tcc->CTRLBSET.bit.LUPD = 1; -// #ifdef SAMD21 -// tcc->CCB[channel].reg = adjusted_duty; -// #endif -// #ifdef SAMD51 -// tcc->CCBUF[channel].reg = adjusted_duty; -// #endif -// tcc->CTRLBCLR.bit.LUPD = 1; -// } + // we do not use PWM_UpdatePwmDutycycle because ... + // * it works in integer percents + // * it can't set the "X" duty cycle + self->duty_cycle = duty; + if (duty == 65535) { + self->duty_scaled = self->pulse_count + 1; + } else { + self->duty_scaled = ((uint32_t)duty * self->pulse_count + self->pulse_count/2) / 65535; + } + switch (self->pwm->channel) { + case kPWM_PwmX: + self->pwm->pwm->SM[self->pwm->submodule].VAL0 = 0; + self->pwm->pwm->SM[self->pwm->submodule].VAL1 = self->duty_scaled; + break; + case kPWM_PwmA: + self->pwm->pwm->SM[self->pwm->submodule].VAL2 = 0; + self->pwm->pwm->SM[self->pwm->submodule].VAL3 = self->duty_scaled; + break; + case kPWM_PwmB: + self->pwm->pwm->SM[self->pwm->submodule].VAL4 = 0; + self->pwm->pwm->SM[self->pwm->submodule].VAL5 = self->duty_scaled; + } + PWM_SetPwmLdok(self->pwm->pwm, 1 << self->pwm->submodule, true); } -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) { -// Tc* tc = tc_insts[t->index]; -// tc_wait_for_sync(tc); -// uint16_t cv = tc->COUNT16.CC[t->wave_output].reg; -// return cv * 0xffff / tc_periods[t->index]; -// } else { -// Tcc* tcc = tcc_insts[t->index]; -// uint8_t channel = tcc_channel(t); -// uint32_t cv = 0; -// -// while (tcc->SYNCBUSY.bit.CTRLB) {} -// -// #ifdef SAMD21 -// // If CCBV (CCB valid) is set, the CCB value hasn't yet been copied -// // to the CC value. -// if ((tcc->STATUS.vec.CCBV & (1 << channel)) != 0) { -// cv = tcc->CCB[channel].reg; -// } else { -// cv = tcc->CC[channel].reg; -// } -// #endif -// #ifdef SAMD51 -// if ((tcc->STATUS.vec.CCBUFV & (1 << channel)) != 0) { -// cv = tcc->CCBUF[channel].reg; -// } else { -// cv = tcc->CC[channel].reg; -// } -// #endif -// -// uint32_t duty_cycle = ((uint64_t) cv) * 0xffff / tcc_periods[t->index]; -// -// return duty_cycle; -// } +uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t *self) { + if (self->duty_cycle == 65535) { + return 65535; + } + return ((uint32_t)self->duty_scaled * 65535 + 65535/2) / self->pulse_count; } -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")); -// } -// const pin_timer_t* t = self->timer; -// uint8_t resolution; -// if (t->is_tc) { -// resolution = 16; -// } else { -// resolution = 24; -// } -// uint32_t system_clock = common_hal_mcu_processor_get_frequency(); -// uint32_t new_top; -// uint8_t new_divisor; -// for (new_divisor = 0; new_divisor < 8; new_divisor++) { -// new_top = (system_clock / prescaler[new_divisor] / frequency) - 1; -// if (new_top < (1u << resolution)) { -// break; -// } -// } -// uint16_t old_duty = common_hal_pwmio_pwmout_get_duty_cycle(self); -// if (t->is_tc) { -// Tc* tc = tc_insts[t->index]; -// uint8_t old_divisor = tc->COUNT16.CTRLA.bit.PRESCALER; -// if (new_divisor != old_divisor) { -// tc_set_enable(tc, false); -// tc->COUNT16.CTRLA.bit.PRESCALER = new_divisor; -// tc_set_enable(tc, true); -// } -// tc_periods[t->index] = new_top; -// #ifdef SAMD21 -// tc->COUNT16.CC[0].reg = new_top; -// #endif -// #ifdef SAMD51 -// while (tc->COUNT16.SYNCBUSY.reg != 0) {} -// tc->COUNT16.CCBUF[0].reg = new_top; -// #endif -// } else { -// Tcc* tcc = tcc_insts[t->index]; -// uint8_t old_divisor = tcc->CTRLA.bit.PRESCALER; -// if (new_divisor != old_divisor) { -// tcc_set_enable(tcc, false); -// tcc->CTRLA.bit.PRESCALER = new_divisor; -// tcc_set_enable(tcc, true); -// } -// while (tcc->SYNCBUSY.reg != 0) {} -// tcc_periods[t->index] = new_top; -// #ifdef SAMD21 -// tcc->PERB.bit.PERB = new_top; -// #endif -// #ifdef SAMD51 -// tcc->PERBUF.bit.PERBUF = new_top; -// #endif -// } +void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, + uint32_t frequency) { + + int pulse_count = calculate_pulse_count(frequency, &self->prescaler); + if (pulse_count == 0) { + mp_raise_ValueError(translate("Invalid PWM frequency")); + } -// common_hal_pwmio_pwmout_set_duty_cycle(self, old_duty); + self->pulse_count = pulse_count; + + // a small glitch can occur when adjusting the prescaler, from the setting + // of CTRL just below to the setting of the Ldok register in + // set_duty_cycle. + uint32_t reg = self->pwm->pwm->SM[self->pwm->submodule].CTRL; + reg &= ~(PWM_CTRL_PRSC_MASK); + reg |= PWM_CTRL_PRSC(self->prescaler); + self->pwm->pwm->SM[self->pwm->submodule].CTRL = reg; + self->pwm->pwm->SM[self->pwm->submodule].VAL1 = self->pulse_count; + + // we need to recalculate the duty cycle. As a side effect of this + 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 system_clock = common_hal_mcu_processor_get_frequency(); -// const pin_timer_t* t = self->timer; -// uint8_t divisor; -// uint32_t top; -// if (t->is_tc) { -// divisor = tc_insts[t->index]->COUNT16.CTRLA.bit.PRESCALER; -// top = tc_periods[t->index]; -// } else { -// divisor = tcc_insts[t->index]->CTRLA.bit.PRESCALER; -// top = tcc_periods[t->index]; -// } -// return (system_clock / prescaler[divisor]) / (top + 1); - return 0; +uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self) { + return PWM_SRC_CLK_FREQ/self->pulse_count/(1 << self->prescaler); } -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/pwmio/PWMOut.h b/ports/mimxrt10xx/common-hal/pwmio/PWMOut.h index d3954de401c0b..fa4ce46780a86 100644 --- a/ports/mimxrt10xx/common-hal/pwmio/PWMOut.h +++ b/ports/mimxrt10xx/common-hal/pwmio/PWMOut.h @@ -37,6 +37,8 @@ typedef struct { const mcu_pin_obj_t *pin; const mcu_pwm_obj_t *pwm; bool variable_frequency; + uint8_t prescaler; + uint16_t duty_cycle, duty_scaled, pulse_count; } pwmio_pwmout_obj_t; void pwmout_reset(void); diff --git a/ports/mimxrt10xx/common-hal/rtc/RTC.c b/ports/mimxrt10xx/common-hal/rtc/RTC.c index 6940a1817d404..aabe2b09f26bf 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 6be38f216ac16..f827651781f10 --- a/ports/mimxrt10xx/common-hal/supervisor/Runtime.c +++ b/ports/mimxrt10xx/common-hal/supervisor/Runtime.c @@ -28,10 +28,10 @@ #include "shared-bindings/supervisor/Runtime.h" #include "supervisor/serial.h" -bool common_hal_get_serial_connected(void) { - return (bool) serial_connected(); +bool common_hal_supervisor_runtime_get_serial_connected(void) { + return (bool)serial_connected(); } -bool common_hal_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); +bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { + return (bool)serial_bytes_available(); } diff --git a/ports/mimxrt10xx/fatfs_port.c b/ports/mimxrt10xx/fatfs_port.c index c65a73a428fcc..e6eee2049511d 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 51e0ef9ff515c..16cc63bc2d0c6 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/mpconfigport.mk b/ports/mimxrt10xx/mpconfigport.mk index b4cc9586ac073..49fc4a2aaa55a 100644 --- a/ports/mimxrt10xx/mpconfigport.mk +++ b/ports/mimxrt10xx/mpconfigport.mk @@ -17,14 +17,18 @@ INTERNAL_LIBM = 1 USB_SERIAL_NUMBER_LENGTH = 32 USB_HIGHSPEED = 1 +# Number of USB endpoint pairs. +USB_NUM_EP = 8 + INTERNAL_FLASH_FILESYSTEM = 1 CIRCUITPY_AUDIOIO = 0 CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_BUSDEVICE = 1 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 CIRCUITPY_NVM = 0 CIRCUITPY_ROTARYIO = 0 CIRCUITPY_COUNTIO = 0 -CIRCUITPY_USB_MIDI = 0 +CIRCUITPY_USB_MIDI = 1 LONGINT_IMPL = MPZ diff --git a/ports/mimxrt10xx/mphalport.c b/ports/mimxrt10xx/mphalport.c index 111e97011e0f0..ff7a880ab7c0e 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 4ba3a24764709..a67e58e3369cf 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 61888fcaa779b..e6354386a9db6 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 a994e154dedd2..bdf3299217b02 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) @@ -134,35 +134,35 @@ const mcu_periph_obj_t mcu_uart_cts_list[4] = { }; const mcu_pwm_obj_t mcu_pwm_list[20] = { - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, 2, &pin_GPIO_02), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, 2, &pin_GPIO_SD_02), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_02_FLEXPWM1_PWM0_A, &pin_GPIO_02), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_SD_02_FLEXPWM1_PWM0_A, &pin_GPIO_SD_02), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, 2, &pin_GPIO_01), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, 2, &pin_GPIO_SD_01), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_01_FLEXPWM1_PWM0_B, &pin_GPIO_01), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_SD_01_FLEXPWM1_PWM0_B, &pin_GPIO_SD_01), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmX, 1, &pin_GPIO_AD_12), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmX, IOMUXC_GPIO_AD_12_FLEXPWM1_PWM0_X, &pin_GPIO_AD_12), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, 2, &pin_GPIO_04), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, 2, &pin_GPIO_SD_04), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_04_FLEXPWM1_PWM1_A, &pin_GPIO_04), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_SD_04_FLEXPWM1_PWM1_A, &pin_GPIO_SD_04), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, 2, &pin_GPIO_03), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, 2, &pin_GPIO_SD_03), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_03_FLEXPWM1_PWM1_B, &pin_GPIO_03), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_SD_03_FLEXPWM1_PWM1_B, &pin_GPIO_SD_03), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmX, 1, &pin_GPIO_AD_11), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmX, IOMUXC_GPIO_AD_11_FLEXPWM1_PWM1_X, &pin_GPIO_AD_11), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, 2, &pin_GPIO_06), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, 2, &pin_GPIO_AD_04), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_06_FLEXPWM1_PWM2_A, &pin_GPIO_06), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_AD_04_FLEXPWM1_PWM2_A, &pin_GPIO_AD_04), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, 2, &pin_GPIO_05), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, 2, &pin_GPIO_AD_03), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_05_FLEXPWM1_PWM2_B, &pin_GPIO_05), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_AD_03_FLEXPWM1_PWM2_B, &pin_GPIO_AD_03), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmX, 1, &pin_GPIO_AD_10), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmX, IOMUXC_GPIO_AD_10_FLEXPWM1_PWM2_X, &pin_GPIO_AD_10), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 2, &pin_GPIO_08), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 2, &pin_GPIO_AD_06), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_08_FLEXPWM1_PWM3_A, &pin_GPIO_08), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_AD_06_FLEXPWM1_PWM3_A, &pin_GPIO_AD_06), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 2, &pin_GPIO_07), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 2, &pin_GPIO_AD_05), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_07_FLEXPWM1_PWM3_B, &pin_GPIO_07), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_AD_05_FLEXPWM1_PWM3_B, &pin_GPIO_AD_05), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmX, 1, &pin_GPIO_AD_09), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmX, IOMUXC_GPIO_AD_09_FLEXPWM1_PWM3_X, &pin_GPIO_AD_09), }; diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pins.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pins.c index cfab35cea8e20..492d1c6f0879a 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 cb9dd34c90328..fb4d04b99294d 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 3d043a14ec2fa..5b21c12c2afb3 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) @@ -199,60 +199,60 @@ const mcu_periph_obj_t mcu_uart_cts_list[10] = { }; const mcu_pwm_obj_t mcu_pwm_list[39] = { - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_EMC_26), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_AD_B1_06), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_EMC_26_FLEXPWM1_PWMA00, &pin_GPIO_EMC_26), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_AD_B1_06_FLEXPWM1_PWMA00, &pin_GPIO_AD_B1_06), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_EMC_24), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_AD_B1_08), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_EMC_24_FLEXPWM1_PWMA01, &pin_GPIO_EMC_24), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_AD_B1_08_FLEXPWM1_PWMA01, &pin_GPIO_AD_B1_08), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_EMC_22), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_AD_B1_10), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_EMC_22_FLEXPWM1_PWMA02, &pin_GPIO_EMC_22), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_AD_B1_10_FLEXPWM1_PWMA02, &pin_GPIO_AD_B1_10), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_EMC_20), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 6, &pin_GPIO_AD_B1_12), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_EMC_20_FLEXPWM1_PWMA03, &pin_GPIO_EMC_20), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_AD_B1_12_FLEXPWM1_PWMA03, &pin_GPIO_AD_B1_12), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_EMC_27), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_AD_B1_07), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_EMC_27_FLEXPWM1_PWMB00, &pin_GPIO_EMC_27), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_AD_B1_07_FLEXPWM1_PWMB00, &pin_GPIO_AD_B1_07), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_EMC_25), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_AD_B1_09), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_EMC_25_FLEXPWM1_PWMB01, &pin_GPIO_EMC_25), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_AD_B1_09_FLEXPWM1_PWMB01, &pin_GPIO_AD_B1_09), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_EMC_23), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_AD_B1_11), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_EMC_23_FLEXPWM1_PWMB02, &pin_GPIO_EMC_23), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_AD_B1_11_FLEXPWM1_PWMB02, &pin_GPIO_AD_B1_11), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 1, &pin_GPIO_EMC_21), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 6, &pin_GPIO_AD_B1_13), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_EMC_21_FLEXPWM1_PWMB03, &pin_GPIO_EMC_21), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_AD_B1_13_FLEXPWM1_PWMB03, &pin_GPIO_AD_B1_13), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmX, 7, &pin_GPIO_EMC_28), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmX, 7, &pin_GPIO_EMC_29), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmX, 7, &pin_GPIO_EMC_30), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmX, IOMUXC_GPIO_EMC_28_FLEXPWM1_PWMX00, &pin_GPIO_EMC_28), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmX, IOMUXC_GPIO_EMC_29_FLEXPWM1_PWMX01, &pin_GPIO_EMC_29), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmX, IOMUXC_GPIO_EMC_30_FLEXPWM1_PWMX02, &pin_GPIO_EMC_30), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_EMC_38), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, 4, &pin_GPIO_AD_B0_14), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_EMC_38_FLEXPWM2_PWMA00, &pin_GPIO_EMC_38), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_AD_B0_14_FLEXPWM2_PWMA00, &pin_GPIO_AD_B0_14), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_EMC_36), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, 4, &pin_GPIO_AD_B0_12), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_EMC_36_FLEXPWM2_PWMA01, &pin_GPIO_EMC_36), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_AD_B0_12_FLEXPWM2_PWMA01, &pin_GPIO_AD_B0_12), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_EMC_30), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, 4, &pin_GPIO_AD_B0_10), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_EMC_30_FLEXPWM2_PWMA02, &pin_GPIO_EMC_30), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_AD_B0_10_FLEXPWM2_PWMA02, &pin_GPIO_AD_B0_10), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_EMC_28), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, 4, &pin_GPIO_AD_B0_06), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_EMC_28_FLEXPWM2_PWMA03, &pin_GPIO_EMC_28), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_AD_B0_06_FLEXPWM2_PWMA03, &pin_GPIO_AD_B0_06), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_EMC_39), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, 4, &pin_GPIO_AD_B0_15), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_EMC_39_FLEXPWM2_PWMB00, &pin_GPIO_EMC_39), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_AD_B0_15_FLEXPWM2_PWMB00, &pin_GPIO_AD_B0_15), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_EMC_37), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, 4, &pin_GPIO_AD_B0_13), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_EMC_37_FLEXPWM2_PWMB01, &pin_GPIO_EMC_37), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_AD_B0_13_FLEXPWM2_PWMB01, &pin_GPIO_AD_B0_13), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_EMC_31), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, 4, &pin_GPIO_AD_B0_11), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_EMC_31_FLEXPWM2_PWMB02, &pin_GPIO_EMC_31), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_AD_B0_11_FLEXPWM2_PWMB02, &pin_GPIO_AD_B0_11), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, 1, &pin_GPIO_EMC_29), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, 4, &pin_GPIO_AD_B0_07), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_EMC_29_FLEXPWM2_PWMB03, &pin_GPIO_EMC_29), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_AD_B0_07_FLEXPWM2_PWMB03, &pin_GPIO_AD_B0_07), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmX, 6, &pin_GPIO_EMC_10), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmX, 6, &pin_GPIO_EMC_11), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmX, 6, &pin_GPIO_EMC_12), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmX, 6, &pin_GPIO_EMC_13), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmX, IOMUXC_GPIO_EMC_10_FLEXPWM2_PWMX00, &pin_GPIO_EMC_10), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmX, IOMUXC_GPIO_EMC_11_FLEXPWM2_PWMX01, &pin_GPIO_EMC_11), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmX, IOMUXC_GPIO_EMC_12_FLEXPWM2_PWMX02, &pin_GPIO_EMC_12), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmX, IOMUXC_GPIO_EMC_13_FLEXPWM2_PWMX03, &pin_GPIO_EMC_13), }; diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pins.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pins.c index a25937cab7a58..fe39f7e19da6e 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 7b9af3a6a5145..1d67956f84783 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 fd1e4ddb85ba4..19ce48f28832b 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) @@ -202,107 +202,107 @@ const mcu_periph_obj_t mcu_uart_cts_list[9] = { }; const mcu_pwm_obj_t mcu_pwm_list[67] = { - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_EMC_23), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_SD_B0_00), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_EMC_23_FLEXPWM1_PWMA00, &pin_GPIO_EMC_23), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_SD_B0_00_FLEXPWM1_PWMA00, &pin_GPIO_SD_B0_00), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_EMC_24), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_SD_B0_01), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_EMC_24_FLEXPWM1_PWMB00, &pin_GPIO_EMC_24), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_SD_B0_01_FLEXPWM1_PWMB00, &pin_GPIO_SD_B0_01), - PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmX, 4, &pin_GPIO_AD_B0_02), + PWM_PIN(PWM1, kPWM_Module_0, kPWM_PwmX, IOMUXC_GPIO_AD_B0_02_FLEXPWM1_PWMX00, &pin_GPIO_AD_B0_02), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_EMC_25), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_SD_B0_02), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_EMC_25_FLEXPWM1_PWMA01, &pin_GPIO_EMC_25), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_SD_B0_02_FLEXPWM1_PWMA01, &pin_GPIO_SD_B0_02), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_EMC_26), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_SD_B0_03), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_EMC_26_FLEXPWM1_PWMB01, &pin_GPIO_EMC_26), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_SD_B0_03_FLEXPWM1_PWMB01, &pin_GPIO_SD_B0_03), - PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmX, 4, &pin_GPIO_AD_B0_03), + PWM_PIN(PWM1, kPWM_Module_1, kPWM_PwmX, IOMUXC_GPIO_AD_B0_03_FLEXPWM1_PWMX01, &pin_GPIO_AD_B0_03), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_EMC_27), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_SD_B0_04), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_EMC_27_FLEXPWM1_PWMA02, &pin_GPIO_EMC_27), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_SD_B0_04_FLEXPWM1_PWMA02, &pin_GPIO_SD_B0_04), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_EMC_28), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_SD_B0_05), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_EMC_28_FLEXPWM1_PWMB02, &pin_GPIO_EMC_28), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_SD_B0_05_FLEXPWM1_PWMB02, &pin_GPIO_SD_B0_05), - PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmX, 4, &pin_GPIO_AD_B0_12), + PWM_PIN(PWM1, kPWM_Module_2, kPWM_PwmX, IOMUXC_GPIO_AD_B0_12_FLEXPWM1_PWMX02, &pin_GPIO_AD_B0_12), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_AD_B0_10), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_EMC_38), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 2, &pin_GPIO_SD_B1_00), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 4, &pin_GPIO_EMC_12), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, 6, &pin_GPIO_B1_00), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_AD_B0_10_FLEXPWM1_PWMA03, &pin_GPIO_AD_B0_10), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_EMC_38_FLEXPWM1_PWMA03, &pin_GPIO_EMC_38), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_SD_B1_00_FLEXPWM1_PWMA03, &pin_GPIO_SD_B1_00), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_EMC_12_FLEXPWM1_PWMA03, &pin_GPIO_EMC_12), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_B1_00_FLEXPWM1_PWMA03, &pin_GPIO_B1_00), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 1, &pin_GPIO_AD_B0_11), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 1, &pin_GPIO_EMC_39), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 2, &pin_GPIO_SD_B1_01), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 4, &pin_GPIO_EMC_13), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, 6, &pin_GPIO_B1_01), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_AD_B0_11_FLEXPWM1_PWMB03, &pin_GPIO_AD_B0_11), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_EMC_39_FLEXPWM1_PWMB03, &pin_GPIO_EMC_39), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_SD_B1_01_FLEXPWM1_PWMB03, &pin_GPIO_SD_B1_01), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_EMC_13_FLEXPWM1_PWMB03, &pin_GPIO_EMC_13), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_B1_01_FLEXPWM1_PWMB03, &pin_GPIO_B1_01), - PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmX, 4, &pin_GPIO_AD_B0_13), + PWM_PIN(PWM1, kPWM_Module_3, kPWM_PwmX, IOMUXC_GPIO_AD_B0_13_FLEXPWM1_PWMX03, &pin_GPIO_AD_B0_13), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_EMC_06), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, 2, &pin_GPIO_B0_06), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_EMC_06_FLEXPWM2_PWMA00, &pin_GPIO_EMC_06), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_B0_06_FLEXPWM2_PWMA00, &pin_GPIO_B0_06), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_EMC_07), - PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, 2, &pin_GPIO_B0_07), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_EMC_07_FLEXPWM2_PWMB00, &pin_GPIO_EMC_07), + PWM_PIN(PWM2, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_B0_07_FLEXPWM2_PWMB00, &pin_GPIO_B0_07), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_EMC_08), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, 2, &pin_GPIO_B0_08), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_EMC_08_FLEXPWM2_PWMA01, &pin_GPIO_EMC_08), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_B0_08_FLEXPWM2_PWMA01, &pin_GPIO_B0_08), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_EMC_09), - PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, 2, &pin_GPIO_B0_09), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_EMC_09_FLEXPWM2_PWMB01, &pin_GPIO_EMC_09), + PWM_PIN(PWM2, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_B0_09_FLEXPWM2_PWMB01, &pin_GPIO_B0_09), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_EMC_10), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, 2, &pin_GPIO_B0_10), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_EMC_10_FLEXPWM2_PWMA02, &pin_GPIO_EMC_10), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_B0_10_FLEXPWM2_PWMA02, &pin_GPIO_B0_10), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_EMC_11), - PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, 2, &pin_GPIO_B0_11), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_EMC_11_FLEXPWM2_PWMB02, &pin_GPIO_EMC_11), + PWM_PIN(PWM2, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_B0_11_FLEXPWM2_PWMB02, &pin_GPIO_B0_11), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, 0, &pin_GPIO_AD_B0_00), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_AD_B0_09), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_EMC_19), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, 2, &pin_GPIO_SD_B1_02), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, 6, &pin_GPIO_B1_02), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_AD_B0_00_FLEXPWM2_PWMA03, &pin_GPIO_AD_B0_00), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_AD_B0_09_FLEXPWM2_PWMA03, &pin_GPIO_AD_B0_09), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_EMC_19_FLEXPWM2_PWMA03, &pin_GPIO_EMC_19), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_SD_B1_02_FLEXPWM2_PWMA03, &pin_GPIO_SD_B1_02), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_B1_02_FLEXPWM2_PWMA03, &pin_GPIO_B1_02), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, 0, &pin_GPIO_AD_B0_01), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, 1, &pin_GPIO_EMC_20), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, 2, &pin_GPIO_SD_B1_03), - PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, 6, &pin_GPIO_B1_03), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_AD_B0_01_FLEXPWM2_PWMB03, &pin_GPIO_AD_B0_01), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_EMC_20_FLEXPWM2_PWMB03, &pin_GPIO_EMC_20), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_SD_B1_03_FLEXPWM2_PWMB03, &pin_GPIO_SD_B1_03), + PWM_PIN(PWM2, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_B1_03_FLEXPWM2_PWMB03, &pin_GPIO_B1_03), - PWM_PIN(PWM3, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_EMC_29), + PWM_PIN(PWM3, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_EMC_29_FLEXPWM3_PWMA00, &pin_GPIO_EMC_29), - PWM_PIN(PWM3, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_EMC_30), + PWM_PIN(PWM3, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_EMC_30_FLEXPWM3_PWMB00, &pin_GPIO_EMC_30), - PWM_PIN(PWM3, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_EMC_31), + PWM_PIN(PWM3, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_EMC_31_FLEXPWM3_PWMA01, &pin_GPIO_EMC_31), - PWM_PIN(PWM3, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_EMC_32), + PWM_PIN(PWM3, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_EMC_32_FLEXPWM3_PWMB01, &pin_GPIO_EMC_32), - PWM_PIN(PWM3, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_EMC_33), + PWM_PIN(PWM3, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_EMC_33_FLEXPWM3_PWMA02, &pin_GPIO_EMC_33), - PWM_PIN(PWM3, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_EMC_34), + PWM_PIN(PWM3, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_EMC_34_FLEXPWM3_PWMB02, &pin_GPIO_EMC_34), - PWM_PIN(PWM3, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_EMC_21), + PWM_PIN(PWM3, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_EMC_21_FLEXPWM3_PWMA03, &pin_GPIO_EMC_21), - PWM_PIN(PWM3, kPWM_Module_3, kPWM_PwmB, 1, &pin_GPIO_EMC_22), + PWM_PIN(PWM3, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_EMC_22_FLEXPWM3_PWMB03, &pin_GPIO_EMC_22), - PWM_PIN(PWM4, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_AD_B1_08), - PWM_PIN(PWM4, kPWM_Module_0, kPWM_PwmA, 1, &pin_GPIO_EMC_00), + PWM_PIN(PWM4, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_AD_B1_08_FLEXPWM4_PWMA00, &pin_GPIO_AD_B1_08), + PWM_PIN(PWM4, kPWM_Module_0, kPWM_PwmA, IOMUXC_GPIO_EMC_00_FLEXPWM4_PWMA00, &pin_GPIO_EMC_00), - PWM_PIN(PWM4, kPWM_Module_0, kPWM_PwmB, 1, &pin_GPIO_EMC_01), + PWM_PIN(PWM4, kPWM_Module_0, kPWM_PwmB, IOMUXC_GPIO_EMC_01_FLEXPWM4_PWMB00, &pin_GPIO_EMC_01), - PWM_PIN(PWM4, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_AD_B1_09), - PWM_PIN(PWM4, kPWM_Module_1, kPWM_PwmA, 1, &pin_GPIO_EMC_02), + PWM_PIN(PWM4, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_AD_B1_09_FLEXPWM4_PWMA01, &pin_GPIO_AD_B1_09), + PWM_PIN(PWM4, kPWM_Module_1, kPWM_PwmA, IOMUXC_GPIO_EMC_02_FLEXPWM4_PWMA01, &pin_GPIO_EMC_02), - PWM_PIN(PWM4, kPWM_Module_1, kPWM_PwmB, 1, &pin_GPIO_EMC_03), + PWM_PIN(PWM4, kPWM_Module_1, kPWM_PwmB, IOMUXC_GPIO_EMC_03_FLEXPWM4_PWMB01, &pin_GPIO_EMC_03), - PWM_PIN(PWM4, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_B1_14), - PWM_PIN(PWM4, kPWM_Module_2, kPWM_PwmA, 1, &pin_GPIO_EMC_04), + PWM_PIN(PWM4, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_B1_14_FLEXPWM4_PWMA02, &pin_GPIO_B1_14), + PWM_PIN(PWM4, kPWM_Module_2, kPWM_PwmA, IOMUXC_GPIO_EMC_04_FLEXPWM4_PWMA02, &pin_GPIO_EMC_04), - PWM_PIN(PWM4, kPWM_Module_2, kPWM_PwmB, 1, &pin_GPIO_EMC_05), + PWM_PIN(PWM4, kPWM_Module_2, kPWM_PwmB, IOMUXC_GPIO_EMC_05_FLEXPWM4_PWMB02, &pin_GPIO_EMC_05), - PWM_PIN(PWM4, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_B1_15), - PWM_PIN(PWM4, kPWM_Module_3, kPWM_PwmA, 1, &pin_GPIO_EMC_17), + PWM_PIN(PWM4, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_B1_15_FLEXPWM4_PWMA03, &pin_GPIO_B1_15), + PWM_PIN(PWM4, kPWM_Module_3, kPWM_PwmA, IOMUXC_GPIO_EMC_17_FLEXPWM4_PWMA03, &pin_GPIO_EMC_17), - PWM_PIN(PWM4, kPWM_Module_3, kPWM_PwmB, 1, &pin_GPIO_EMC_18), + PWM_PIN(PWM4, kPWM_Module_3, kPWM_PwmB, IOMUXC_GPIO_EMC_18_FLEXPWM4_PWMB03, &pin_GPIO_EMC_18), }; diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pins.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pins.c index ce098ea2bce2c..0e440b6b63648 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 9b9713bb4d5d5..1b808b0b18db5 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/periph.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/periph.h @@ -31,38 +31,46 @@ #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; uint8_t mux_mode; + uint8_t input_idx; + uint32_t input_reg; 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, \ -} +#define PWM_PIN(p_pwm, p_submodule, p_channel, p_iomuxc, p_pin) \ + PWM_PIN_(p_pwm, p_submodule, p_channel, p_iomuxc, p_pin) + //----------------------------------------------------------// + // supplied by the expansion of p_iomuxc into multiple args // +#define PWM_PIN_(p_pwm, p_submodule, p_channel, p_mux_reg, p_mux_mode, p_input_reg, p_input_idx, p_config_reg, p_pin)\ + { \ + .pwm = p_pwm, \ + .submodule = p_submodule, \ + .channel = p_channel, \ + .mux_mode = p_mux_mode, \ + .input_reg = p_input_reg, \ + .input_idx = p_input_idx, \ + .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 7168854a5e92f..d6d12771c5dac 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 bd471f93055f2..251e6f9acd693 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); - - if (status != kStatus_Success) - { + 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) { 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 9c0d9f89562d4..84c478bcfb3f1 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 33a85d2b72b5b..2493252d78e9b 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 01656a819c470..ea706d8a8c842 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 91135289c85c4..57f038799004f 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/Makefile b/ports/nrf/Makefile index 278625e92d3e1..0b44f054f13fd 100755 --- a/ports/nrf/Makefile +++ b/ports/nrf/Makefile @@ -177,6 +177,7 @@ SRC_C += \ sd_mutex.c \ supervisor/shared/memory.c +ifneq ($(CIRCUITPY_USB),0) # USB source files for nrf52840 ifeq ($(MCU_SUB_VARIANT),nrf52840) SRC_C += \ @@ -187,6 +188,7 @@ ifeq ($(MCU_SUB_VARIANT),nrf52833) SRC_C += \ lib/tinyusb/src/portable/nordic/nrf5x/dcd_nrf5x.c endif +endif # CIRCUITPY_USB ifeq ($(CIRCUITPY_NETWORK),1) CFLAGS += -DMICROPY_PY_NETWORK=1 diff --git a/ports/nrf/background.c b/ports/nrf/background.c index 10543ddb21aae..269bf6737f648 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 67c6f34687ac1..cb923227b21d8 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,36 @@ 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) { + #if CIRCUITPY_USB // 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; - - tusb_hal_nrf_power_event(usbevt); - } + 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); + } break; + #endif // 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; - - default: - 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; } } @@ -134,7 +136,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 +156,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 d69f83e6ef6eb..e7649fceee8a8 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 1e7a319bdd5f8..df645686782ac 100644 --- a/ports/nrf/bluetooth/ble_uart.c +++ b/ports/nrf/bluetooth/ble_uart.c @@ -40,7 +40,7 @@ #include "shared-bindings/_bleio/Service.h" #include "shared-bindings/_bleio/UUID.h" -#if CIRCUITPY_SERIAL_BLE +#if CIRCUITPY_REPL_BLE static const char default_name[] = "CP-REPL"; // max 8 chars or uuid won't fit in adv data static const char NUS_UUID[] = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"; @@ -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, }; @@ -190,4 +188,4 @@ void mp_hal_stdout_tx_strn(const char *str, size_t len) { } } -#endif // CIRCUITPY_SERIAL_BLE +#endif // CIRCUITPY_REPL_BLE diff --git a/ports/nrf/bluetooth/ringbuffer.h b/ports/nrf/bluetooth/ringbuffer.h index 9a06e7ccc407c..baf273293184c 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 e2abcd7ad8a0a..2ee2c74dce14d 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 1b4820dc3d6fc..64e610a2f2867 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 6750e742f7072..f5a8199a98ef8 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 9cb577cc85667..45b78a75ed7ef 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 7fb3920244da3..c4c8322ca1957 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; - - 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; - } +__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; + } } #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 394d8d189726e..1a7a51ac1e3a0 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 edaf6641f80e8..d04bec3fbf2d1 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 88c93180c83da..3504959135413 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 e0c80e278c350..1c7f3e1f3b832 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 6badee98e56df..7e9bf748d519f 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 530959b9d67ad..8e43a6102f15c 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 1f79cc3c8c22f..c2fa90f668b2b 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_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_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; + } -__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; + 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_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_pending_irq = NVIC_GetPendingIRQ(IRQn); +__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; - } - 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_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_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_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_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_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_GetPriority(IRQn_Type IRQn, uint32_t * p_priority) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_priority = (NVIC_GetPriority(IRQn) & 0xFF); +__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; - } - 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_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_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_SystemReset(void) { + NVIC_SystemReset(); + return NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN; } -__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)) - { +__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t *p_is_nested_critical_region) { 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(); + 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; +} - 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 282e762e004fd..8a9979af2bbd7 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 beb4d3a541c05..e3790a9f4a2ae 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 - { - 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 + uint8_t callback_action; /**< The action requested by the application when returning from the signal callback, see @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION. */ + union { - 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 292c692982837..e95c298e087f5 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 d17ac9a596be8..aa5abd5ef9ed9 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 1b4820dc3d6fc..64e610a2f2867 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 d657fd6c116fe..3a3ccc4950a6a 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 c3928844182bd..cb760720e1925 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 7fb3920244da3..c4c8322ca1957 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; - - 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; - } +__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; + } } #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 394d8d189726e..1a7a51ac1e3a0 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 7587350cf9f48..933f398b57bfa 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 88c93180c83da..3504959135413 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 42e09fc87c59d..34132e21017fd 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 6badee98e56df..7e9bf748d519f 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 530959b9d67ad..8e43a6102f15c 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 1f79cc3c8c22f..c2fa90f668b2b 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_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_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; + } -__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; + 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_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_pending_irq = NVIC_GetPendingIRQ(IRQn); +__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; - } - 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_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_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_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_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_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_GetPriority(IRQn_Type IRQn, uint32_t * p_priority) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_priority = (NVIC_GetPriority(IRQn) & 0xFF); +__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; - } - 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_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_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_SystemReset(void) { + NVIC_SystemReset(); + return NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN; } -__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)) - { +__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t *p_is_nested_critical_region) { 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(); + 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; +} - 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 6834599e8713f..24001fb12a828 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 3751d133f506c..2baf305c7a977 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 - { - 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 + uint8_t callback_action; /**< The action requested by the application when returning from the signal callback, see @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION. */ + union { - 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 231a54f941c42..293001eccf0a1 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 78179332815e6..688cfb4ded1bc 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 78179332815e6..688cfb4ded1bc 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/TG-Watch/mpconfigboard.h b/ports/nrf/boards/TG-Watch/mpconfigboard.h index 07a607b3d7c79..1377c921ee5af 100644 --- a/ports/nrf/boards/TG-Watch/mpconfigboard.h +++ b/ports/nrf/boards/TG-Watch/mpconfigboard.h @@ -30,27 +30,27 @@ #define MICROPY_HW_BOARD_NAME "TG-Watch" #define MICROPY_HW_MCU_NAME "nRF52840" -#define MICROPY_HW_NEOPIXEL (&pin_P0_16) -#define MICROPY_HW_LED_STATUS (&pin_P1_15) - -// TG-Gui requires a deeper call stack than normal CircuitPython +// TG-Gui requires a deeper call stack than normal CircuitPython, this is intentional overkill #define CIRCUITPY_PYSTACK_SIZE 8192 // 1536 is the normal size, (32 bytes/frame * 48 frames) -#define BOARD_HAS_CRYSTAL 0 + +// the board has a 32mhz crystal but NOT a 32khz one +#define BOARD_HAS_32KHZ_XTAL 0 +#define BOARD_HAS_CRYSTAL 1 #if QSPI_FLASH_FILESYSTEM -#define MICROPY_QSPI_DATA0 NRF_GPIO_PIN_MAP(0, 17) -#define MICROPY_QSPI_DATA1 NRF_GPIO_PIN_MAP(0, 22) -#define MICROPY_QSPI_DATA2 NRF_GPIO_PIN_MAP(0, 23) -#define MICROPY_QSPI_DATA3 NRF_GPIO_PIN_MAP(0, 21) -#define MICROPY_QSPI_SCK NRF_GPIO_PIN_MAP(0, 19) -#define MICROPY_QSPI_CS NRF_GPIO_PIN_MAP(0, 20) + #define MICROPY_QSPI_DATA0 NRF_GPIO_PIN_MAP(0, 17) + #define MICROPY_QSPI_DATA1 NRF_GPIO_PIN_MAP(0, 22) + #define MICROPY_QSPI_DATA2 NRF_GPIO_PIN_MAP(0, 23) + #define MICROPY_QSPI_DATA3 NRF_GPIO_PIN_MAP(0, 21) + #define MICROPY_QSPI_SCK NRF_GPIO_PIN_MAP(0, 19) + #define MICROPY_QSPI_CS NRF_GPIO_PIN_MAP(0, 20) #endif #if SPI_FLASH_FILESYSTEM -#define SPI_FLASH_MOSI_PIN &pin_P0_17 -#define SPI_FLASH_MISO_PIN &pin_P0_22 -#define SPI_FLASH_SCK_PIN &pin_P0_19 -#define SPI_FLASH_CS_PIN &pin_P0_20 + #define SPI_FLASH_MOSI_PIN &pin_P0_17 + #define SPI_FLASH_MISO_PIN &pin_P0_22 + #define SPI_FLASH_SCK_PIN &pin_P0_19 + #define SPI_FLASH_CS_PIN &pin_P0_20 #endif #define DEFAULT_I2C_BUS_SCL (&pin_P0_11) diff --git a/ports/nrf/boards/TG-Watch/mpconfigboard.mk b/ports/nrf/boards/TG-Watch/mpconfigboard.mk index f1aac6d71ecd8..8a191c1534a8b 100644 --- a/ports/nrf/boards/TG-Watch/mpconfigboard.mk +++ b/ports/nrf/boards/TG-Watch/mpconfigboard.mk @@ -6,8 +6,7 @@ USB_MANUFACTURER = "TG-Techie" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 -EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q128JV_SQ" +EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q128JVxQ" FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_BusDevice FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register diff --git a/ports/nrf/boards/aramcon2_badge/board.c b/ports/nrf/boards/aramcon2_badge/board.c new file mode 100644 index 0000000000000..1759822a2ac8f --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Uri Shaked + * Copyright (c) 2021 Benjamin Meisels + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} diff --git a/ports/nrf/boards/aramcon2_badge/mpconfigboard.h b/ports/nrf/boards/aramcon2_badge/mpconfigboard.h new file mode 100644 index 0000000000000..7691d1e46107d --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/mpconfigboard.h @@ -0,0 +1,68 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Uri Shaked + * Copyright (c) 2021 Benjamin Meisels + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include "nrfx/hal/nrf_gpio.h" + +#define MICROPY_HW_BOARD_NAME "ARAMCON2 Badge" +#define MICROPY_HW_MCU_NAME "nRF52840" + +#define MICROPY_HW_LED_STATUS (&pin_P1_11) + +// Board does not have a 32kHz crystal. It does have a 32MHz crystal. +#define BOARD_HAS_32KHZ_XTAL (0) + +#ifdef QSPI_FLASH_FILESYSTEM +#define MICROPY_QSPI_DATA0 NRF_GPIO_PIN_MAP(0, 22) +#define MICROPY_QSPI_DATA1 NRF_GPIO_PIN_MAP(0, 20) +#define MICROPY_QSPI_DATA2 NRF_GPIO_PIN_MAP(1, 4) +#define MICROPY_QSPI_DATA3 NRF_GPIO_PIN_MAP(1, 6) +#define MICROPY_QSPI_SCK NRF_GPIO_PIN_MAP(1, 0) +#define MICROPY_QSPI_CS NRF_GPIO_PIN_MAP(1, 2) +#endif + +#ifdef SPI_FLASH_FILESYSTEM +#define SPI_FLASH_MOSI_PIN &pin_P0_20 +#define SPI_FLASH_MISO_PIN &pin_P0_22 +#define SPI_FLASH_SCK_PIN &pin_P1_00 +#define SPI_FLASH_CS_PIN &pin_P1_02 +#endif + +#define CIRCUITPY_BOOT_BUTTON (&pin_P0_29) + +#define BOARD_USER_SAFE_MODE_ACTION translate("pressing the left button at start up\n") + +#define CIRCUITPY_AUTORELOAD_DELAY_MS 500 + +#define CIRCUITPY_INTERNAL_NVM_SIZE (4096) + +#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) + +#define DEFAULT_I2C_BUS_SCL (&pin_P0_28) +#define DEFAULT_I2C_BUS_SDA (&pin_P0_03) + +#define DEFAULT_SPI_BUS_SCK (&pin_P0_01) +#define DEFAULT_SPI_BUS_MOSI (&pin_P1_10) +#define DEFAULT_SPI_BUS_MISO (&pin_P1_09) diff --git a/ports/nrf/boards/aramcon2_badge/mpconfigboard.mk b/ports/nrf/boards/aramcon2_badge/mpconfigboard.mk new file mode 100644 index 0000000000000..514712f489642 --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x239A +USB_PID = 0x807C +USB_PRODUCT = "ARAMCON2 Badge" +USB_MANUFACTURER = "ARAMCON Badge Team" + +MCU_CHIP = nrf52840 + +QSPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY_DISPLAYIO = 1 diff --git a/ports/nrf/boards/aramcon2_badge/pins.c b/ports/nrf/boards/aramcon2_badge/pins.c new file mode 100644 index 0000000000000..0a44f0d5a94ed --- /dev/null +++ b/ports/nrf/boards/aramcon2_badge/pins.c @@ -0,0 +1,42 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR_UP_BUTTON), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_LEFT_BUTTON), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_DOWN_BUTTON), MP_ROM_PTR(&pin_P1_13) }, + { MP_ROM_QSTR(MP_QSTR_RIGHT_BUTTON), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_ACTION_BUTTON), MP_ROM_PTR(&pin_P0_10) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_P1_11) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P0_03) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P0_01) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_P1_10) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_P1_09) }, + + { MP_ROM_QSTR(MP_QSTR_GPIO1), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_GPIO2), MP_ROM_PTR(&pin_P0_05) }, + + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_P0_00) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_P0_13) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_P0_24) }, + + { MP_ROM_QSTR(MP_QSTR_DISP_BUSY), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_DISP_CS), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_DISP_DC), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_DISP_RESET), MP_ROM_PTR(&pin_P0_06) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_P0_08) }, + + { MP_ROM_QSTR(MP_QSTR_VIBRATION_MOTOR), MP_ROM_PTR(&pin_P0_17) }, + + { MP_ROM_QSTR(MP_QSTR_BATTERY_SENSE), MP_ROM_PTR(&pin_P0_30) }, + + { 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_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/aramcon_badge_2019/mpconfigboard.mk b/ports/nrf/boards/aramcon_badge_2019/mpconfigboard.mk index 09252ab4b7432..06cd9633d1762 100644 --- a/ports/nrf/boards/aramcon_badge_2019/mpconfigboard.mk +++ b/ports/nrf/boards/aramcon_badge_2019/mpconfigboard.mk @@ -6,7 +6,6 @@ USB_MANUFACTURER = "ARAMCON Badge Team" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" CIRCUITPY_DISPLAYIO = 1 diff --git a/ports/nrf/boards/arduino_nano_33_ble/board.c b/ports/nrf/boards/arduino_nano_33_ble/board.c index d1689e9ddc16c..8359b394659d1 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 b6fb04f06c48d..ee999b650b28f 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/bastble/mpconfigboard.mk b/ports/nrf/boards/bastble/mpconfigboard.mk index eca900de775fa..417c993589573 100644 --- a/ports/nrf/boards/bastble/mpconfigboard.mk +++ b/ports/nrf/boards/bastble/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "ElectronicCats" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" 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 6970294ecc0d4..d1f26b0b56de3 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 ff731d8f987fa..a0013e721512e 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/circuitplayground_bluefruit/mpconfigboard.mk b/ports/nrf/boards/circuitplayground_bluefruit/mpconfigboard.mk index 6b5c0424f93c5..bc00790376e13 100644 --- a/ports/nrf/boards/circuitplayground_bluefruit/mpconfigboard.mk +++ b/ports/nrf/boards/circuitplayground_bluefruit/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Adafruit Industries LLC" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" diff --git a/ports/nrf/boards/circuitplayground_bluefruit/pins.c b/ports/nrf/boards/circuitplayground_bluefruit/pins.c index d0d9659db79a5..f600282528f94 100644 --- a/ports/nrf/boards/circuitplayground_bluefruit/pins.c +++ b/ports/nrf/boards/circuitplayground_bluefruit/pins.c @@ -52,6 +52,7 @@ STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_POWER_SWITCH), MP_ROM_PTR(&pin_P0_06) }, { MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_P1_14) }, { MP_ROM_QSTR(MP_QSTR_L), MP_ROM_PTR(&pin_P1_14) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_P1_14) }, diff --git a/ports/nrf/boards/clue_nrf52840_express/board.c b/ports/nrf/boards/clue_nrf52840_express/board.c index cd46ce75d3257..b5c0f56ba385e 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/clue_nrf52840_express/mpconfigboard.mk b/ports/nrf/boards/clue_nrf52840_express/mpconfigboard.mk index 16cb20824791a..f94e49e473366 100644 --- a/ports/nrf/boards/clue_nrf52840_express/mpconfigboard.mk +++ b/ports/nrf/boards/clue_nrf52840_express/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Adafruit Industries LLC" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" diff --git a/ports/nrf/boards/electronut_labs_blip/board.c b/ports/nrf/boards/electronut_labs_blip/board.c index 78179332815e6..688cfb4ded1bc 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 78179332815e6..688cfb4ded1bc 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 78179332815e6..688cfb4ded1bc 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_bluefruit_sense/mpconfigboard.mk b/ports/nrf/boards/feather_bluefruit_sense/mpconfigboard.mk index 5813e6136be6e..6d0c13e4546f8 100644 --- a/ports/nrf/boards/feather_bluefruit_sense/mpconfigboard.mk +++ b/ports/nrf/boards/feather_bluefruit_sense/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Adafruit Industries LLC" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" diff --git a/ports/nrf/boards/feather_nrf52840_express/board.c b/ports/nrf/boards/feather_nrf52840_express/board.c index 78179332815e6..688cfb4ded1bc 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/feather_nrf52840_express/mpconfigboard.mk b/ports/nrf/boards/feather_nrf52840_express/mpconfigboard.mk index 84861a1f0bf03..b291203e2f833 100644 --- a/ports/nrf/boards/feather_nrf52840_express/mpconfigboard.mk +++ b/ports/nrf/boards/feather_nrf52840_express/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Adafruit Industries LLC" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" diff --git a/ports/nrf/boards/hiibot_bluefi/board.c b/ports/nrf/boards/hiibot_bluefi/board.c index a3fd5cf12907e..daca539619c0f 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 4b7a884cfa5cf..3c0af124e100b 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/mpconfigboard.mk b/ports/nrf/boards/hiibot_bluefi/mpconfigboard.mk index d601243486182..71e2a9da238ca 100644 --- a/ports/nrf/boards/hiibot_bluefi/mpconfigboard.mk +++ b/ports/nrf/boards/hiibot_bluefi/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "HiiBot" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q16JV_IQ" +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" diff --git a/ports/nrf/boards/hiibot_bluefi/pins.c b/ports/nrf/boards/hiibot_bluefi/pins.c index c7879c4c21b79..f871d5db86d91 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 78179332815e6..688cfb4ded1bc 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 78179332815e6..688cfb4ded1bc 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/itsybitsy_nrf52840_express/mpconfigboard.mk b/ports/nrf/boards/itsybitsy_nrf52840_express/mpconfigboard.mk index d5587f4b94a35..57b39b512b40e 100644 --- a/ports/nrf/boards/itsybitsy_nrf52840_express/mpconfigboard.mk +++ b/ports/nrf/boards/itsybitsy_nrf52840_express/mpconfigboard.mk @@ -9,5 +9,4 @@ MCU_CHIP = nrf52840 CIRCUITPY_BITBANG_APA102 = 1 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" diff --git a/ports/nrf/boards/makerdiary_m60_keyboard/board.c b/ports/nrf/boards/makerdiary_m60_keyboard/board.c index 78179332815e6..688cfb4ded1bc 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/mpconfigboard.mk b/ports/nrf/boards/makerdiary_m60_keyboard/mpconfigboard.mk index fc630e5bbe4a3..e7547af717462 100644 --- a/ports/nrf/boards/makerdiary_m60_keyboard/mpconfigboard.mk +++ b/ports/nrf/boards/makerdiary_m60_keyboard/mpconfigboard.mk @@ -6,7 +6,6 @@ USB_MANUFACTURER = "Makerdiary" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25R6435F" CIRCUITPY_ENABLE_MPY_NATIVE = 1 diff --git a/ports/nrf/boards/makerdiary_m60_keyboard/pins.c b/ports/nrf/boards/makerdiary_m60_keyboard/pins.c index fc85fa24b030d..82e9dfc5a0960 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_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_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_BTN), MP_ROM_PTR(&pin_P0_27) }, + { 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_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_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_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 569106ec2ab9f..51e453c1f006a 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/mpconfigboard.mk b/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/mpconfigboard.mk index 4e6aebc8e8c1a..cd19c25b1d9d1 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/mpconfigboard.mk +++ b/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/mpconfigboard.mk @@ -6,7 +6,6 @@ USB_MANUFACTURER = "Makerdiary" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25R6435F" CIRCUITPY_ENABLE_MPY_NATIVE = 1 diff --git a/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/pins.c b/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/pins.c index 18928683308fb..a8eaab092e0ab 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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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 78179332815e6..688cfb4ded1bc 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/mpconfigboard.mk b/ports/nrf/boards/makerdiary_nrf52840_mdk/mpconfigboard.mk index d69bc8235725f..7da9ed1896b8d 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_mdk/mpconfigboard.mk +++ b/ports/nrf/boards/makerdiary_nrf52840_mdk/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "makerdiary" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25R6435F" diff --git a/ports/nrf/boards/makerdiary_nrf52840_mdk/pins.c b/ports/nrf/boards/makerdiary_nrf52840_mdk/pins.c index 34f487b1ded97..bd0e6e4802559 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_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_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_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_BUTTON_USR), MP_ROM_PTR(&pin_P1_00) }, + { 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_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_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_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_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 78179332815e6..688cfb4ded1bc 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 d46f369422d55..05813bd04a122 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 78179332815e6..688cfb4ded1bc 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/metro_nrf52840_express/mpconfigboard.mk b/ports/nrf/boards/metro_nrf52840_express/mpconfigboard.mk index b972bcbed7a1e..ef0992a742d2a 100644 --- a/ports/nrf/boards/metro_nrf52840_express/mpconfigboard.mk +++ b/ports/nrf/boards/metro_nrf52840_express/mpconfigboard.mk @@ -6,7 +6,6 @@ USB_MANUFACTURER = "Adafruit Industries LLC" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" CIRCUITPY__EVE = 1 diff --git a/ports/nrf/boards/nice_nano/board.c b/ports/nrf/boards/nice_nano/board.c index 78179332815e6..688cfb4ded1bc 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 5f61947007fa1..fd605e12f0248 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 0c96eb61ef5ab..92fb165b50f63 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 20abf4e2a91a5..1522e45c9ace2 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/ohs2020_badge/mpconfigboard.mk b/ports/nrf/boards/ohs2020_badge/mpconfigboard.mk index 7d2c6de987324..045939e65252c 100644 --- a/ports/nrf/boards/ohs2020_badge/mpconfigboard.mk +++ b/ports/nrf/boards/ohs2020_badge/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "OSHWA" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = "W25Q128JV_SQ" +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" diff --git a/ports/nrf/boards/particle_argon/board.c b/ports/nrf/boards/particle_argon/board.c index a41f0ae06ed23..94ee5d69575fd 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_argon/mpconfigboard.mk b/ports/nrf/boards/particle_argon/mpconfigboard.mk index f8d3d2aca228c..eaed5527c1e7c 100644 --- a/ports/nrf/boards/particle_argon/mpconfigboard.mk +++ b/ports/nrf/boards/particle_argon/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Particle" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25L3233F" diff --git a/ports/nrf/boards/particle_boron/board.c b/ports/nrf/boards/particle_boron/board.c index a41f0ae06ed23..94ee5d69575fd 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_boron/mpconfigboard.mk b/ports/nrf/boards/particle_boron/mpconfigboard.mk index eada97a730993..26fe7b83db604 100644 --- a/ports/nrf/boards/particle_boron/mpconfigboard.mk +++ b/ports/nrf/boards/particle_boron/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Particle" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25L3233F" diff --git a/ports/nrf/boards/particle_xenon/board.c b/ports/nrf/boards/particle_xenon/board.c index a41f0ae06ed23..94ee5d69575fd 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/particle_xenon/mpconfigboard.mk b/ports/nrf/boards/particle_xenon/mpconfigboard.mk index 6062da378f726..0722c4ac6596f 100644 --- a/ports/nrf/boards/particle_xenon/mpconfigboard.mk +++ b/ports/nrf/boards/particle_xenon/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Particle" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25L3233F" diff --git a/ports/nrf/boards/pca10056/board.c b/ports/nrf/boards/pca10056/board.c index 78179332815e6..688cfb4ded1bc 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 1a0c5aabbcaa2..4db357697073d 100644 --- a/ports/nrf/boards/pca10056/examples/buttons.py +++ b/ports/nrf/boards/pca10056/examples/buttons.py @@ -17,9 +17,9 @@ 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/pca10056/mpconfigboard.mk b/ports/nrf/boards/pca10056/mpconfigboard.mk index f24e6f6670ee4..48f68a30ae15c 100644 --- a/ports/nrf/boards/pca10056/mpconfigboard.mk +++ b/ports/nrf/boards/pca10056/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "Nordic Semiconductor" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25R6435F" diff --git a/ports/nrf/boards/pca10059/board.c b/ports/nrf/boards/pca10059/board.c index 78179332815e6..688cfb4ded1bc 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 a41f0ae06ed23..94ee5d69575fd 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 4639a208b497e..00c10fc2559c7 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/pca10100/mpconfigboard.mk b/ports/nrf/boards/pca10100/mpconfigboard.mk index c8cba2877cf5a..74080a1ed9eee 100644 --- a/ports/nrf/boards/pca10100/mpconfigboard.mk +++ b/ports/nrf/boards/pca10100/mpconfigboard.mk @@ -9,6 +9,7 @@ INTERNAL_FLASH_FILESYSTEM = 1 CIRCUITPY_AUDIOMP3 = 0 CIRCUITPY_BITBANGIO = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_BUSIO = 1 CIRCUITPY_COUNTIO = 0 CIRCUITPY_DISPLAYIO = 0 @@ -29,6 +30,7 @@ CIRCUITPY_BUSDEVICE = 0 MICROPY_PY_ASYNC_AWAIT = 0 SUPEROPT_GC = 0 +SUPEROPT_VM = 0 # Override optimization to keep binary small OPTIMIZATION_FLAGS = -Os diff --git a/ports/nrf/boards/pitaya_go/board.c b/ports/nrf/boards/pitaya_go/board.c index 78179332815e6..688cfb4ded1bc 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/mpconfigboard.mk b/ports/nrf/boards/pitaya_go/mpconfigboard.mk index 247ddd8ac5bc8..14e2108b78ec7 100644 --- a/ports/nrf/boards/pitaya_go/mpconfigboard.mk +++ b/ports/nrf/boards/pitaya_go/mpconfigboard.mk @@ -7,5 +7,4 @@ USB_MANUFACTURER = "Makerdiary" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "MX25R6435F" diff --git a/ports/nrf/boards/pitaya_go/pins.c b/ports/nrf/boards/pitaya_go/pins.c index ba333fc2be4ac..c0f2976a5778e 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 78179332815e6..688cfb4ded1bc 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 a41f0ae06ed23..94ee5d69575fd 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 a89f540b04eeb..9361e8ef23890 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/simmel/mpconfigboard.mk b/ports/nrf/boards/simmel/mpconfigboard.mk index 6bc05a7f0849e..b4a1417a539c9 100644 --- a/ports/nrf/boards/simmel/mpconfigboard.mk +++ b/ports/nrf/boards/simmel/mpconfigboard.mk @@ -3,20 +3,19 @@ USB_PID = 0xc051 USB_PRODUCT = "Simmel" USB_MANUFACTURER = "Betrusted" -CIRCUITPY_DEVICES="CDC,MSC,HID" - MCU_CHIP = nrf52833 # SPI_FLASH_FILESYSTEM = 1 -# EXTERNAL_FLASH_DEVICE_COUNT = 1 # EXTERNAL_FLASH_DEVICES = "MX25R1635F" INTERNAL_FLASH_FILESYSTEM = 1 CIRCUITPY_AESIO = 1 CIRCUITPY_AUDIOMP3 = 0 +CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_BUSDEVICE = 0 CIRCUITPY_BUSIO = 1 +CIRCUITPY_COUNTIO = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_ERRNO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 @@ -31,6 +30,7 @@ CIRCUITPY_RTC = 1 CIRCUITPY_SDCARDIO = 0 CIRCUITPY_TOUCHIO = 0 CIRCUITPY_ULAB = 0 +CIRCUITPY_USB_CDC = 0 CIRCUITPY_USB_MIDI = 0 CIRCUITPY_WATCHDOG = 1 diff --git a/ports/nrf/boards/sparkfun_nrf52840_micromod/README.md b/ports/nrf/boards/sparkfun_nrf52840_micromod/README.md new file mode 100644 index 0000000000000..094102c27797d --- /dev/null +++ b/ports/nrf/boards/sparkfun_nrf52840_micromod/README.md @@ -0,0 +1,70 @@ +# SparkFun MicroMod nRF52840 Processor + +Featuring the nRF52840 SoC from Nordic Semiconductor, the [SparkFun MicroMod nRF52840 Processor](https://www.sparkfun.com/products/16984) offers a powerful combination of ARM Cortex-M4 CPU and 2.4 GHz Bluetooth transceiver in the MicroMod form-factor with the M.2 MicroMod connector to allow you to plug in a compatible MicroMod Carrier Board with any number of peripherals. + +The MicroMod nRF52840 Processor features the same Raytac MDBT50Q-P1M found on our [Pro nRF52840 Mini](https://www.sparkfun.com/products/15025). This module includes an integrated trace antenna, fits the IC to an FCC-approved footprint along with including decoupling and timing mechanisms that would need to be designed into a circuit using the bare nRF52840 IC. The Bluetooth transceiver included on the nRF52840 boasts a BT 5.1 stack and supports Bluetooth 5, Bluetooth mesh, IEEE 802.15.4 (Zigbee & Thread) and 2.4Ghz RF wireless protocols (including Nordic's proprietary RF protocol) allowing you to pick which option works best for your application. + +We've also routed two I2C buses, 2 SPI buses, eleven GPIO, dedicated digital, analog, PWM & PDM pins along with multiple serial UARTS to cover nearly all of your peripheral needs. + +## CircuitPython Pin Defs + +CircuitPython pin definitions, while simialr to other boards represent a slight departure from just the typical `A` and `D` pin definitions. The majority of general pins are labled as `G` (or alternatively, `BUS`,) as the MicroMod system they build on uses those names to specify pins that may not be specficially analog or digital. + +This can be somewhat confusing, especially around the analog pins. Here's a quick pin-map. This pin map will use the label either on the [SparkFun MicroMod ATP Carrier Board](https://www.sparkfun.com/products/16885), or the pin name on the [graphical datasheet](https://cdn.sparkfun.com/assets/learn_tutorials/1/4/0/1/MicroMod_nRF52840_v1.0_Graphical_Datasheet.pdf). Some of the aditional aliases are just names to make naming consistent (e.g.: RTS/CTS), but they also can refer to additional functionality a pin may have (e.g.: NFC pins) + +MicroMod Pin # | ATP Pin Label | Pin Definition | Additional Definitons | Pin/Port Reference | Notes +:--------------|:--------------|:--------------|:-----------------------|:-------------------|:------ +8 | G11 | | | (Not Connected) | +10 | D0 | D0 | | P0_27 | +11 | BOOT | BOOT | BUTTON1 | P0_07 | +12 | SDA | SDA | | P0_08 | +13 | RTS1 | RTS | RTS1 | P1_02 | +14 | SCL | SCL | | P0_11 | +15 | CTS1 | CTS | CTS1 | P1_09 | +16 | /I2C INT | I2C_INT | P0_15 | +17 | TX | TX | TX1 | P1_03 | +18 | D1 | D1 | CAM_TRIG | P1_08 | +19 | RX | RX | RX1 | P1_10 | +20 | RX2 | RX2 | | P1_05 | +22 | TX2 | TX2 | | P1_07 | +32 | PWM0 | PWM0 | P0_06 | +34 | A0 | A0 | ADC0 | P0_04 | Attached to AIN2 +38 | A1 | A1 | ADC1 | P0_05 | Attached to AIN3 +40 | G0 | G0 | BUS0 | P0_29 | Attached to AIN5 +42 | G1 | G1 | BUS1 | P0_03 | Attached to AIN1 +44 | G2 | G2 | BUS2 | P1_13 | +46 | G3 | G3 | BUS3 | P1_12 | +47 | PWM1 | PWM1 | P0_16 | +48 | G4 | G4 | BUS4 | P1_11 | +49 | BATT_VIN | BATT_VIN3 | | P0_30 | Attached to AIN6, will be battery voltage / 3. | +50 | PDM_CLK | PDM_CLK | | P0_25 | +51 | SDA1 | SDA1 | | P1_01 | +52 | PDM_DATA | PDM_DATA | | P0_26 | +53 | SCL1 | SCL1 | | P0_24 | +55 | /CS | CS | | P0_20 | +57 | SCK | SCK | | P0_28 | Attached to AIN4 +59 | COPI | COPI | MOSI | P0_31 | Attached to AIN7 +61 | CIPO | CIPO | MISO | P0_02 | +63 | G10 | G10 | NFC2, ADC_DP, CAM_VSYNC | P0_10 | Attached to NFC2 +65 | G9 | G9 | NFC1, ADC_DM, CAM_HSYNC | P0_09 | Attached to NFC1 +67 | G8 | G8 | | P1_14 | +69 | G7 | G7 | BUS7 | P1_04 | +71 | G6 | G6 | BUS6 | P1_06 | +73 | G5 | G5 | BUS5 | P0_15 | + +## Peripheral Naming + +CircuitPython attempts to stay in line with the naming of the serial peripheral naming in the MicroMod system. The bare UART pins are also named 1. The UART 2 pins are named 2. However, the I2C names on MicroMod are and 1. Perhaps this will change in the future, but as of [Interface v1](https://cdn.sparkfun.com/assets/learn_tutorials/1/2/0/6/SparkFun_MicroMod_Interface_v1.0_-_Pin_Descriptions.pdf), it may lead to some confusion. + + +## Bootloader Notes + +The MicroMod nRF52840 Processor needs to have the [Adafruit nRF52 UF2 bootloader](https://github.com/adafruit/Adafruit_nRF52_Bootloader/pull/194) flashed on it. [[TODO: LINK TO BUILD]] + +## Hardware Reference + +The MicroMod nRF52840 Processor hardware layout is open source: + +* [Schematic](https://cdn.sparkfun.com/assets/f/0/9/9/e/MicroMod_Processor_Board-nRF52840.pdf) +* [Eagle Files](https://cdn.sparkfun.com/assets/3/0/5/d/a/MicroMod_Processor_Board-nRF52840.zip) +* [Hookup Guide](https://learn.sparkfun.com/tutorials/micromod-nrf52840-processor-hookup-guide) diff --git a/ports/nrf/boards/sparkfun_nrf52840_micromod/board.c b/ports/nrf/boards/sparkfun_nrf52840_micromod/board.c new file mode 100644 index 0000000000000..688cfb4ded1bc --- /dev/null +++ b/ports/nrf/boards/sparkfun_nrf52840_micromod/board.c @@ -0,0 +1,38 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + +} diff --git a/ports/nrf/boards/sparkfun_nrf52840_micromod/mpconfigboard.h b/ports/nrf/boards/sparkfun_nrf52840_micromod/mpconfigboard.h new file mode 100644 index 0000000000000..c53fc45d22e6b --- /dev/null +++ b/ports/nrf/boards/sparkfun_nrf52840_micromod/mpconfigboard.h @@ -0,0 +1,53 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Glenn Ruben Bakke + * Copyright (c) 2021 Chris Marc Dailey + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "nrfx/hal/nrf_gpio.h" + +#define MICROPY_HW_BOARD_NAME "SparkFun MicroMod nRF52840" +#define MICROPY_HW_MCU_NAME "nRF52840" + +#define DEFAULT_I2C_BUS_SCL (&pin_P0_11) +#define DEFAULT_I2C_BUS_SDA (&pin_P0_08) + +#define DEFAULT_SPI_BUS_SCK (&pin_P0_28) +#define DEFAULT_SPI_BUS_MOSI (&pin_P0_31) +#define DEFAULT_SPI_BUS_MISO (&pin_P0_02) + +#define DEFAULT_UART_BUS_RX (&pin_P1_10) +#define DEFAULT_UART_BUS_TX (&pin_P1_03) + +#define BOARD_HAS_32KHZ_XTAL (1) +#define BOARD_HAS_CRYSTAL (1) + +#if QSPI_FLASH_FILESYSTEM +#define MICROPY_QSPI_DATA0 NRF_GPIO_PIN_MAP(0, 14) // Labeled 'SPI_COPI1/SDIO_CMD' in schematic. +#define MICROPY_QSPI_DATA1 NRF_GPIO_PIN_MAP(0, 21) // Labeled 'SPI_CIPO1/SDIO_DATA0' in schematic. +#define MICROPY_QSPI_DATA2 NRF_GPIO_PIN_MAP(0, 23) // Labeled 'SPI_DATA2' in schematic. +#define MICROPY_QSPI_DATA3 NRF_GPIO_PIN_MAP(1, 0) // Labeled 'SPI_CS1/SDIO_DATA3' in schematic. +#define MICROPY_QSPI_SCK NRF_GPIO_PIN_MAP(0, 19) // Labeled 'SPI_SCK1/SDIO_CLK' in schematic. +#define MICROPY_QSPI_CS NRF_GPIO_PIN_MAP(0, 12) // Labeled 'FLASH_CS' in schematic. +#endif // QSPI_FLASH_FILESYSTEM diff --git a/ports/nrf/boards/sparkfun_nrf52840_micromod/mpconfigboard.mk b/ports/nrf/boards/sparkfun_nrf52840_micromod/mpconfigboard.mk new file mode 100644 index 0000000000000..21ca20825a111 --- /dev/null +++ b/ports/nrf/boards/sparkfun_nrf52840_micromod/mpconfigboard.mk @@ -0,0 +1,10 @@ +USB_VID = 0x1B4F +USB_PID = 0x0021 +USB_PRODUCT = "SFE_nRF52840_MicroMod" +USB_MANUFACTURER = "SparkFun Electronics" + +MCU_CHIP = nrf52840 + +QSPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICE_COUNT = 1 +EXTERNAL_FLASH_DEVICES = "W25Q128JVxM" diff --git a/ports/nrf/boards/sparkfun_nrf52840_micromod/pins.c b/ports/nrf/boards/sparkfun_nrf52840_micromod/pins.c new file mode 100644 index 0000000000000..65700f24e4b75 --- /dev/null +++ b/ports/nrf/boards/sparkfun_nrf52840_micromod/pins.c @@ -0,0 +1,113 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_module_globals_table[] = { + // D pins (D0-D1) + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_P0_27) }, // 0.27 - D0 + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_P1_08) }, // 1.08 - D1 | CAM_TRIG + { MP_ROM_QSTR(MP_QSTR_CAM_TRIG), MP_ROM_PTR(&pin_P1_08) }, // CAM_TRIG alias + + // A pins (A0-A1) + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_P0_04) }, // 0.04 - A0 | ADC0 (AIN2) + { MP_ROM_QSTR(MP_QSTR_ADC0), MP_ROM_PTR(&pin_P0_04) }, // ADC0 alias + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_P0_05) }, // 0.05 - A1 | ADC1 (AIN3) + { MP_ROM_QSTR(MP_QSTR_ADC1), MP_ROM_PTR(&pin_P0_05) }, // ADC1 alias + + // G pins (G0-G11, G11 NC) + { MP_ROM_QSTR(MP_QSTR_G0), MP_ROM_PTR(&pin_P0_29) }, // 0.29 - G0 | GPIO0 | BUS0 (AIN5) + { MP_ROM_QSTR(MP_QSTR_BUS0), MP_ROM_PTR(&pin_P0_29) }, // BUS0 alias + { MP_ROM_QSTR(MP_QSTR_G1), MP_ROM_PTR(&pin_P0_03) }, // 0.03 - G1 | GPIO1 | BUS1 (AIN1) + { MP_ROM_QSTR(MP_QSTR_BUS1), MP_ROM_PTR(&pin_P0_03) }, // BUS1 alias + { MP_ROM_QSTR(MP_QSTR_G2), MP_ROM_PTR(&pin_P1_13) }, // 1.13 - G2 | GPIO2 | BUS2 + { MP_ROM_QSTR(MP_QSTR_BUS2), MP_ROM_PTR(&pin_P1_13) }, // BUS2 alias + { MP_ROM_QSTR(MP_QSTR_G3), MP_ROM_PTR(&pin_P1_12) }, // 1.12 - G3 | GPIO3 | BUS3 + { MP_ROM_QSTR(MP_QSTR_BUS3), MP_ROM_PTR(&pin_P1_12) }, // BUS3 alias + { MP_ROM_QSTR(MP_QSTR_G4), MP_ROM_PTR(&pin_P1_11) }, // 1.11 - G4 | GPIO4 | BUS4 + { MP_ROM_QSTR(MP_QSTR_BUS4), MP_ROM_PTR(&pin_P1_11) }, // BUS4 alias + { MP_ROM_QSTR(MP_QSTR_G5), MP_ROM_PTR(&pin_P0_17) }, // 0.17 - G5 | GPIO5 | BUS5 + { MP_ROM_QSTR(MP_QSTR_BUS5), MP_ROM_PTR(&pin_P0_17) }, // BUS5 alias + { MP_ROM_QSTR(MP_QSTR_G6), MP_ROM_PTR(&pin_P1_06) }, // 1.06 - G6 | GPIO6 | BUS6 + { MP_ROM_QSTR(MP_QSTR_BUS6), MP_ROM_PTR(&pin_P1_06) }, // BUS6 alias + { MP_ROM_QSTR(MP_QSTR_G7), MP_ROM_PTR(&pin_P1_04) }, // 1.04 - G7 | GPIO7 | BUS7 + { MP_ROM_QSTR(MP_QSTR_BUS7), MP_ROM_PTR(&pin_P1_04) }, // BUS7 alias + { MP_ROM_QSTR(MP_QSTR_G8), MP_ROM_PTR(&pin_P1_14) }, // 1.14 - G8 | GPIO8 + { MP_ROM_QSTR(MP_QSTR_G9), MP_ROM_PTR(&pin_P0_09) }, // 0.09 - G9 | GPIO9/NFC1 | ADC_D- | CAM_HSYNC (NFC1) + { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, // NFC1 alias + { MP_ROM_QSTR(MP_QSTR_ADC_DM), MP_ROM_PTR(&pin_P0_09) }, // ADC_DM alias + { MP_ROM_QSTR(MP_QSTR_CAM_HSYNC), MP_ROM_PTR(&pin_P0_09) }, // CAM_HSYNC alias + { MP_ROM_QSTR(MP_QSTR_G10), MP_ROM_PTR(&pin_P0_10) }, // 0.10 - G10 | GPIO10/NFC2 | ADC_D+ | CAM_VSYNC (NFC2) + { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, // NFC2 alias + { MP_ROM_QSTR(MP_QSTR_ADC_DP), MP_ROM_PTR(&pin_P0_10) }, // ADC_DP alias + { MP_ROM_QSTR(MP_QSTR_CAM_VSYNC), MP_ROM_PTR(&pin_P0_10) }, // CAM_VSYNC alias + // NC - G11 + + // PWM pins (PWM0-PWM1) + { MP_ROM_QSTR(MP_QSTR_PWM0), MP_ROM_PTR(&pin_P0_06) }, // 0.06 - PWM0 + { MP_ROM_QSTR(MP_QSTR_PWM1), MP_ROM_PTR(&pin_P0_16) }, // 0.16 - PWM1 + + // PDM + { MP_ROM_QSTR(MP_QSTR_PDM_CLK), MP_ROM_PTR(&pin_P0_25) }, // 0.25 - PDM_CLK | AUD_BCLK + { MP_ROM_QSTR(MP_QSTR_PDM_DATA), MP_ROM_PTR(&pin_P0_26) }, // 0.26 - PDM_DATA | AUD_LRCLK + + // Battery Voltage Monitor + { MP_ROM_QSTR(MP_QSTR_BATT_VIN3), MP_ROM_PTR(&pin_P0_30) }, // 0.30 - BATT_VIN/3 (AIN6) + + // I2C + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P0_08) }, // 0.08 - SDA + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P0_11) }, // 0.11 - SCL (TRACEDATA2) + + { MP_ROM_QSTR(MP_QSTR_I2C_INT), MP_ROM_PTR(&pin_P0_15) }, // 0.15 - I2C_INT + + { MP_ROM_QSTR(MP_QSTR_SDA1), MP_ROM_PTR(&pin_P1_01) }, // 1.01 - SDA1 + { MP_ROM_QSTR(MP_QSTR_SCL1), MP_ROM_PTR(&pin_P0_24) }, // 0.24 - SCL1 + + // SPI + { MP_ROM_QSTR(MP_QSTR_CIPO), MP_ROM_PTR(&pin_P0_02) }, // 0.02 - CIPO | SPI_CIPO + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_P0_02) }, // MISO alias + { MP_ROM_QSTR(MP_QSTR_COPI), MP_ROM_PTR(&pin_P0_31) }, // 0.31 - COPI | SPI_COPI (AIN7) + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_P0_31) }, // MOSI alias + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P0_28) }, // 0.28 - SCK | SPI_SCK (AIN4) + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_P0_20) }, // 0.20 - /CS | SPI_/CS + + // QSPI, used by flash on this board, but is broken out + // on the MicroMod connector, to to the SDIO pins. + { MP_ROM_QSTR(MP_QSTR_SDIO_CLK), MP_ROM_PTR(&pin_P0_19) }, // 0.00 - SDIO SCK | Used as: QSPI flash SCK + { MP_ROM_QSTR(MP_QSTR_SPI_SCK1), MP_ROM_PTR(&pin_P0_19) }, // SPI_SCK1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_CMD), MP_ROM_PTR(&pin_P0_14) }, // 0.00 - SDIO CMD | Used as: QSPI flash D0 (or SDI) + { MP_ROM_QSTR(MP_QSTR_SPI_COPI1), MP_ROM_PTR(&pin_P0_14) }, // SPI_COPI1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA0), MP_ROM_PTR(&pin_P0_21) },// 0.00 - SDIO DATA0 | Used as: QSPI flash D1 (or SDO) + { MP_ROM_QSTR(MP_QSTR_SPI_CIPO1), MP_ROM_PTR(&pin_P0_21) }, // SPI_CIPO1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA1), MP_ROM_PTR(&pin_P0_22) },// 0.00 - SDIO DATA1 | Unused for flash. + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA2), MP_ROM_PTR(&pin_P0_23) },// 0.00 - SDIO DATA2 | Used as: QSPI flash D2 + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA3), MP_ROM_PTR(&pin_P1_00) },// 0.00 - SDIO DATA3 | Use das: QSPI flash D3 (or /HOLD) + { MP_ROM_QSTR(MP_QSTR_SPI_CS1), MP_ROM_PTR(&pin_P1_00) }, // SPI_CS1 alias + + // Reset Pin + { MP_ROM_QSTR(MP_QSTR_RESET), MP_ROM_PTR(&pin_P1_14) }, // 0.18 - /RESET (NRESET) + + // LED + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_P0_13) }, // 0.13 - LED_BUILTIN | STAT | Blue LED + + // Button + { MP_ROM_QSTR(MP_QSTR_BUTTON1), MP_ROM_PTR(&pin_P0_07) }, // 0.07 - /BOOT [Active Low] (TRACECLK) - Is button on carriers. + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_P0_07) }, // BOOT alias + + // UART + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_P1_10) }, // 1.10 - UART RX | RX1 + { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_P1_10) }, // RX1 alias + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_P1_03) }, // 1.03 - UART TX | TX1 + { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_P1_03) }, // TX1 alias + { MP_ROM_QSTR(MP_QSTR_CTS), MP_ROM_PTR(&pin_P1_09) }, // 1.09 - UART CTS | CTS1 (TRACEDATA3) + { MP_ROM_QSTR(MP_QSTR_CTS1), MP_ROM_PTR(&pin_P1_09) }, // CTS1 alias + { MP_ROM_QSTR(MP_QSTR_RTS), MP_ROM_PTR(&pin_P1_02) }, // 1.02 - UART RTS | RTS1 + { MP_ROM_QSTR(MP_QSTR_RTS1), MP_ROM_PTR(&pin_P1_02) }, // RTS1 alias + + { MP_ROM_QSTR(MP_QSTR_RX2), MP_ROM_PTR(&pin_P1_05) }, // 1.05 - UART RX | RX2 + { MP_ROM_QSTR(MP_QSTR_TX2), MP_ROM_PTR(&pin_P1_07) }, // 1.07 - UART TX | TX2 + + // Board Objects + { 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_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/sparkfun_nrf52840_mini/board.c b/ports/nrf/boards/sparkfun_nrf52840_mini/board.c index 78179332815e6..688cfb4ded1bc 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 e7b61db584e4c..026b566ef84fc 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 78179332815e6..688cfb4ded1bc 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 c130cd8c06bd9..8ddeeb72aa452 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 78179332815e6..688cfb4ded1bc 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/boards/tinkeringtech_scoutmakes_azul/mpconfigboard.mk b/ports/nrf/boards/tinkeringtech_scoutmakes_azul/mpconfigboard.mk index e8bd636ad9280..7808b165752da 100644 --- a/ports/nrf/boards/tinkeringtech_scoutmakes_azul/mpconfigboard.mk +++ b/ports/nrf/boards/tinkeringtech_scoutmakes_azul/mpconfigboard.mk @@ -6,5 +6,4 @@ USB_MANUFACTURER = "TinkeringTech LLC" MCU_CHIP = nrf52840 QSPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C" diff --git a/ports/nrf/common-hal/_bleio/Adapter.c b/ports/nrf/common-hal/_bleio/Adapter.c index 10794c16a8ba2..26555e24da727 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); @@ -147,6 +147,8 @@ STATIC uint32_t ble_stack_enable(void) { ble_conf.gap_cfg.role_count_cfg.periph_role_count = BLEIO_PERIPH_ROLE_COUNT; // central_role_count costs 648 bytes for 1 to 2, then ~1250 for each further increment. ble_conf.gap_cfg.role_count_cfg.central_role_count = BLEIO_CENTRAL_ROLE_COUNT; + // The number of concurrent pairing processes. Takes 392 bytes. + ble_conf.gap_cfg.role_count_cfg.central_sec_count = BLE_GAP_ROLE_COUNT_CENTRAL_SEC_DEFAULT; err_code = sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &ble_conf, sd_ram_end); if (err_code != NRF_SUCCESS) { return err_code; @@ -211,20 +213,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 +244,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; @@ -283,8 +285,12 @@ STATIC bool adapter_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { ble_drv_remove_event_handler(connection_on_ble_evt, connection); connection->conn_handle = BLE_CONN_HANDLE_INVALID; connection->pair_status = PAIR_NOT_PAIRED; + + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "disconnected %02x\n", ble_evt->evt.gap_evt.params.disconnected.reason); + #endif 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 +316,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 +330,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) { @@ -345,8 +351,11 @@ void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enable } else { err_code = sd_softdevice_disable(); } + + #if CIRCUITPY_USB // Re-init USB hardware init_usb_hardware(); + #endif check_nrf_error(err_code); @@ -401,7 +410,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 +418,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 +444,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 +461,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 +471,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 +526,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 +555,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 +630,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 +660,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 +758,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 +839,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 837e5c111ef05..68a8b4864464e 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 c0f0372c3fb8b..f651b93b6bceb 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); @@ -131,6 +131,10 @@ size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *sel return 0; } +size_t common_hal_bleio_characteristic_get_max_length(bleio_characteristic_obj_t *self) { + return self->max_length; +} + void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, mp_buffer_info_t *bufinfo) { // Do GATT operations only if this characteristic has been added to a registered service. if (self->handle != BLE_GATT_HANDLE_INVALID) { @@ -139,7 +143,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 +220,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 +242,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 132e392dd7b52..b17327da4790b 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 36fda0bb357f3..7e0b7a10e9d76 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 @@ -325,8 +325,7 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { } void bleio_connection_clear(bleio_connection_internal_t *self) { - mp_obj_list_clear(MP_OBJ_FROM_PTR(self->remote_service_list)); - + self->remote_service_list = NULL; self->conn_handle = BLE_CONN_HANDLE_INVALID; self->pair_status = PAIR_NOT_PAIRED; self->is_central = false; @@ -391,7 +390,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 +407,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 +429,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 +451,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 +480,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 +489,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 +525,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 +534,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 +582,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 +592,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 +713,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 +734,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 +747,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 180b2727ca79c..eb095c993a688 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 d848659fce296..7ec287260bcd0 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 6d587984cac04..260e20514bca7 100644 --- a/ports/nrf/common-hal/_bleio/PacketBuffer.c +++ b/ports/nrf/common-hal/_bleio/PacketBuffer.c @@ -42,7 +42,8 @@ STATIC void write_to_ringbuf(bleio_packet_buffer_obj_t *self, uint8_t *data, uint16_t len) { if (len + sizeof(uint16_t) > ringbuf_capacity(&self->ringbuf)) { - // This shouldn't happen. + // This shouldn't happen but can if our buffer size was much smaller than + // the writes the client actually makes. return; } // Push all the data onto the ring buffer. @@ -51,13 +52,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); } @@ -106,20 +107,23 @@ STATIC uint32_t queue_next_write(bleio_packet_buffer_obj_t *self) { STATIC bool packet_buffer_on_ble_client_evt(ble_evt_t *ble_evt, void *param) { const uint16_t evt_id = ble_evt->header.evt_id; + bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *)param; + if (evt_id == BLE_GAP_EVT_DISCONNECTED && self->conn_handle == ble_evt->evt.gap_evt.conn_handle) { + self->conn_handle = BLE_CONN_HANDLE_INVALID; + } // Check if this is a GATTC event so we can make sure the conn_handle is valid. if (evt_id < BLE_GATTC_EVT_BASE || evt_id > BLE_GATTC_EVT_LAST) { return false; } uint16_t conn_handle = ble_evt->evt.gattc_evt.conn_handle; - 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 +147,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 +164,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 +189,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, size_t max_packet_size) { self->characteristic = characteristic; self->client = self->characteristic->service->is_remote; @@ -203,8 +207,11 @@ void common_hal_bleio_packet_buffer_construct( self->conn_handle = BLE_CONN_HANDLE_INVALID; } + // Cap the packet size to our implementation limits. + self->max_packet_size = MIN(max_packet_size, BLE_GATTS_VAR_ATTR_LEN_MAX - 3); + if (incoming) { - if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + characteristic->max_length), false)) { + if (!ringbuf_alloc(&self->ringbuf, buffer_size * (sizeof(uint16_t) + self->max_packet_size), false)) { mp_raise_ValueError(translate("Buffer too large and unable to allocate")); } } @@ -213,8 +220,8 @@ void common_hal_bleio_packet_buffer_construct( self->packet_queued = false; self->pending_index = 0; self->pending_size = 0; - self->outgoing[0] = m_malloc(characteristic->max_length, false); - self->outgoing[1] = m_malloc(characteristic->max_length, false); + self->outgoing[0] = m_malloc(self->max_packet_size, false); + self->outgoing[1] = m_malloc(self->max_packet_size, false); } else { self->outgoing[0] = NULL; self->outgoing[1] = NULL; @@ -249,6 +256,9 @@ void common_hal_bleio_packet_buffer_construct( } mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len) { + if (self->conn_handle == BLE_CONN_HANDLE_INVALID) { + mp_raise_ConnectionError(translate("Not connected")); + } if (ringbuf_num_filled(&self->ringbuf) < 2) { return 0; } @@ -259,7 +269,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 +277,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 +291,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")); } @@ -290,19 +300,28 @@ mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, u } uint16_t outgoing_packet_length = common_hal_bleio_packet_buffer_get_outgoing_packet_length(self); - if (len + header_len > outgoing_packet_length) { + uint16_t total_len = len + header_len; + if (total_len > outgoing_packet_length) { // Supplied data will not fit in a single BLE packet. - mp_raise_ValueError(translate("Total data to write is larger than outgoing_packet_length")); + mp_raise_ValueError_varg(translate("Total data to write is larger than %q"), MP_QSTR_outgoing_packet_length); } + if (total_len > self->max_packet_size) { + // Supplied data will not fit in a single BLE packet. + mp_raise_ValueError_varg(translate("Total data to write is larger than %q"), MP_QSTR_max_packet_size); + } + outgoing_packet_length = MIN(outgoing_packet_length, self->max_packet_size); if (len + self->pending_size > outgoing_packet_length) { // No room to append len bytes to packet. Wait until we get a free buffer, // and keep checking that we haven't been disconnected. - while (self->pending_size != 0 && self->conn_handle != BLE_CONN_HANDLE_INVALID) { + while (self->pending_size != 0 && + self->conn_handle != BLE_CONN_HANDLE_INVALID && + !mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; } } - if (self->conn_handle == BLE_CONN_HANDLE_INVALID) { + if (self->conn_handle == BLE_CONN_HANDLE_INVALID || + mp_hal_is_interrupted()) { return -1; } @@ -311,7 +330,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); @@ -351,8 +370,7 @@ mp_int_t common_hal_bleio_packet_buffer_get_incoming_packet_length(bleio_packet_ if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { 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); + return common_hal_bleio_connection_get_max_packet_length(connection); } } // There's no current connection, so we don't know the MTU, and @@ -382,7 +400,8 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { 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), + return MIN(MIN(common_hal_bleio_connection_get_max_packet_length(connection), + self->max_packet_size), self->characteristic->max_length); } } @@ -390,7 +409,20 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ // we can't tell what the largest outgoing packet length would be. return -1; } - return self->characteristic->max_length; + // If we are talking to a remote service, we'll be bound by the MTU. (We don't actually + // know the max size of the remote characteristic.) + if (self->characteristic->service != NULL && + self->characteristic->service->is_remote) { + // We are talking to a remote service so we're writing. + if (self->conn_handle != BLE_CONN_HANDLE_INVALID) { + 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->max_packet_size); + } + } + } + return MIN(self->characteristic->max_length, self->max_packet_size); } bool common_hal_bleio_packet_buffer_deinited(bleio_packet_buffer_obj_t *self) { diff --git a/ports/nrf/common-hal/_bleio/PacketBuffer.h b/ports/nrf/common-hal/_bleio/PacketBuffer.h index 699291749fb37..6f2626565bc96 100644 --- a/ports/nrf/common-hal/_bleio/PacketBuffer.h +++ b/ports/nrf/common-hal/_bleio/PacketBuffer.h @@ -39,11 +39,12 @@ 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). volatile uint16_t conn_handle; + uint16_t max_packet_size; uint8_t pending_index; uint8_t write_type; bool client; diff --git a/ports/nrf/common-hal/_bleio/Service.c b/ports/nrf/common-hal/_bleio/Service.c index 3159d3392f7f0..74e74fac9fde0 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 0c79e980eea2e..399bf23ed204c 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 5293f7ad1433a..72a8e9137093f 100644 --- a/ports/nrf/common-hal/_bleio/__init__.c +++ b/ports/nrf/common-hal/_bleio/__init__.c @@ -46,6 +46,9 @@ void check_nrf_error(uint32_t err_code) { return; } switch (err_code) { + case NRF_ERROR_NO_MEM: + mp_raise_msg(&mp_type_MemoryError, translate("Nordic system firmware out of memory")); + return; case NRF_ERROR_TIMEOUT: mp_raise_msg(&mp_type_TimeoutError, NULL); return; @@ -53,7 +56,7 @@ void check_nrf_error(uint32_t err_code) { mp_raise_ConnectionError(translate("Not connected")); return; default: - mp_raise_bleio_BluetoothError(translate("Unknown soft device error: %04x"), err_code); + mp_raise_bleio_BluetoothError(translate("Unknown system firmware error: %04x"), err_code); break; } } @@ -120,7 +123,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 +150,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 +159,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 +187,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 081ba992f3a46..0c39bfe423165 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 cb8e7c427bcd7..c0dbe2aec0698 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 dbcc5281ce477..2f7bede165b9e 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 a268bb54e4041..0f5fe3208fe3c 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 adafa15d5c913..7afa773d3091d 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 34eecf8d540d0..ded03c07c2832 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 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 { 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 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 ddd34174b215f..47d7365777ae5 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); } @@ -259,15 +266,16 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, if (max_buffer_length > UINT16_MAX) { mp_raise_ValueError_varg(translate("Buffer length %d too big. It must be less than %d"), max_buffer_length, UINT16_MAX); } - self->buffer_length = (uint16_t)max_buffer_length; - self->buffers[0] = m_malloc(self->buffer_length * 2 * sizeof(uint16_t), false); - if (!self->single_buffer) - self->buffers[1] = m_malloc(self->buffer_length * 2 * sizeof(uint16_t), false); + 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) { + 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/audiopwmio/PWMAudioOut.h b/ports/nrf/common-hal/audiopwmio/PWMAudioOut.h index fdd6289a43290..be147bb9b9c46 100644 --- a/ports/nrf/common-hal/audiopwmio/PWMAudioOut.h +++ b/ports/nrf/common-hal/audiopwmio/PWMAudioOut.h @@ -35,7 +35,6 @@ typedef struct { NRF_PWM_Type *pwm; uint16_t *buffers[2]; - uint16_t buffer_length; uint16_t quiescent_value; uint16_t scale; diff --git a/ports/nrf/common-hal/busio/I2C.c b/ports/nrf/common-hal/busio/I2C.c index 37cb192df8868..de9417a6cc3e7 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); @@ -131,21 +129,21 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, const mcu_pin_obj_t * if (!nrf_gpio_pin_read(sda->number) || !nrf_gpio_pin_read(scl->number)) { reset_pin_number(sda->number); reset_pin_number(scl->number); - mp_raise_RuntimeError(translate("SDA or SCL needs a pull up")); + 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 b75d15f00fdb2..04bc578684cfd 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 1cf074955f9ce..309e1bce18824 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 ef3ac9531e494..796ff59f93aa0 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 6ecf7e0ba3dbb..6436cb4e7001c 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,35 +122,39 @@ 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) { + mp_raise_ValueError(translate("Invalid word/bit length")); + } + if ((rs485_dir != NULL) || (rs485_invert)) { mp_raise_ValueError(translate("RS485 Not yet supported on this device")); } // 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; @@ -161,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")); } @@ -192,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 @@ -209,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 { @@ -244,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); @@ -260,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")); } @@ -274,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; } } @@ -293,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; } @@ -304,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); } @@ -324,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); } @@ -345,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/countio/Counter.c b/ports/nrf/common-hal/countio/Counter.c new file mode 100644 index 0000000000000..94fadae7c3e52 --- /dev/null +++ b/ports/nrf/common-hal/countio/Counter.c @@ -0,0 +1,66 @@ + +#include "common-hal/countio/Counter.h" +#include "nrfx_gpiote.h" + +// obj array to map pin number -> self since nrfx hide the mapping +static countio_counter_obj_t *_countio_objs[NUMBER_OF_PINS]; + +static void _intr_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { + countio_counter_obj_t *self = _countio_objs[pin]; + if (!self) { + return; + } + self->count += 1; +} + +void common_hal_countio_counter_construct(countio_counter_obj_t* self, + const mcu_pin_obj_t* pin_a) { + + self->pin_a = pin_a->number; + _countio_objs[self->pin_a] = self; + + self->count = 0; + + nrfx_gpiote_in_config_t cfg = { + .sense = NRF_GPIOTE_POLARITY_HITOLO, + .pull = NRF_GPIO_PIN_PULLUP, + .is_watcher = false, + .hi_accuracy = true, + .skip_gpio_setup = false + }; + + nrfx_gpiote_in_init(self->pin_a, &cfg, _intr_handler); + nrfx_gpiote_in_event_enable(self->pin_a, true); + + claim_pin(pin_a); + +} + +bool common_hal_countio_counter_deinited(countio_counter_obj_t* self) { + return self->pin_a == NO_PIN; +} + +void common_hal_countio_counter_deinit(countio_counter_obj_t* self) { + if (common_hal_countio_counter_deinited(self)) { + return; + } + _countio_objs[self->pin_a] = NULL; + + nrfx_gpiote_in_event_disable(self->pin_a); + nrfx_gpiote_in_uninit(self->pin_a); + reset_pin_number(self->pin_a); + self->pin_a = NO_PIN; +} + +mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t* self) { + return self->count; +} + +void common_hal_countio_counter_set_count(countio_counter_obj_t* self, + mp_int_t new_count) { + self->count = new_count; +} + +void common_hal_countio_counter_reset(countio_counter_obj_t* self){ + self->count = 0; +} diff --git a/ports/nrf/common-hal/countio/Counter.h b/ports/nrf/common-hal/countio/Counter.h new file mode 100644 index 0000000000000..cf40a63a02580 --- /dev/null +++ b/ports/nrf/common-hal/countio/Counter.h @@ -0,0 +1,15 @@ + +#ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_COUNTIO_COUNTER_H +#define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_COUNTIO_COUNTER_H + +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint8_t pin_a; + mp_int_t count; +} countio_counter_obj_t; + +#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_COUNTIO_COUNT_H diff --git a/ports/nrf/common-hal/countio/__init__.c b/ports/nrf/common-hal/countio/__init__.c new file mode 100644 index 0000000000000..b95b20d1534ea --- /dev/null +++ b/ports/nrf/common-hal/countio/__init__.c @@ -0,0 +1 @@ +//No countio module functions diff --git a/ports/nrf/common-hal/digitalio/DigitalInOut.c b/ports/nrf/common-hal/digitalio/DigitalInOut.c index 2a72151b77859..b42d7dc704675 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 31ee1f48e4b6d..7e0aea0d63d6c 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, uint32_t frequency) { 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 5c10d3d42a961..30a0c7e61e458 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 23d6e23bfe787..aea4f63eae594 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 735ed90ccaf7d..888ab6a8c461f 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 ab5f29b5db71d..b31c4c12d7b82 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 06aac9409dc1f..d84cc584552f8 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 8062937f4b70b..c8aa44cd12c9d 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 6b2f04a61bf45..5af2cc5636310 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 c048d557781cf..b3609a59257c3 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 b2ad00a5ca421..5a0f10596cea2 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 ca44a20b4a134..f8f877d965c8e 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 da5263ac9cd64..cdd0e669092a2 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 f40dbea5c8263..17f498ba8e81b 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 a9d8964883433..e49214631b92c 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]; - - 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; + 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->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 e910baa765228..f96c5e4f8138b 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 e13b761abf40d..238fee9764a6b 100644 --- a/ports/nrf/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/nrf/common-hal/rgbmatrix/RGBMatrix.c @@ -32,7 +32,7 @@ extern void _PM_IRQ_HANDLER(void); -void *common_hal_rgbmatrix_timer_allocate() { +void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self) { nrfx_timer_t *timer = nrf_peripherals_allocate_timer_or_throw(); nrf_peripherals_timer_never_reset(timer); return timer->p_reg; @@ -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 24d86f1779f68..8101b9c6bc3d6 100644 --- a/ports/nrf/common-hal/rgbmatrix/RGBMatrix.h +++ b/ports/nrf/common-hal/rgbmatrix/RGBMatrix.h @@ -27,9 +27,11 @@ #ifndef MICROPY_INCLUDED_NRF_COMMON_HAL_RGBMATRIX_RGBMATRIX_H #define MICROPY_INCLUDED_NRF_COMMON_HAL_RGBMATRIX_RGBMATRIX_H -void *common_hal_rgbmatrix_timer_allocate(void); -void common_hal_rgbmatrix_timer_enable(void*); -void common_hal_rgbmatrix_timer_disable(void*); -void common_hal_rgbmatrix_timer_free(void*); +#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 *); #endif diff --git a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c index 28f563da6fb37..8b46c3bd79d3a 100644 --- a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c @@ -25,6 +25,7 @@ */ #include "common-hal/rotaryio/IncrementalEncoder.h" +#include "shared-module/rotaryio/IncrementalEncoder.h" #include "nrfx_gpiote.h" #include "py/runtime.h" @@ -36,32 +37,19 @@ 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; - - // 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--; - // ignore other state transitions + if (!self) { + return; + } - self->state = new_state; + uint8_t new_state = + ((uint8_t) nrf_gpio_pin_read(self->pin_a) << 1) | + (uint8_t) nrf_gpio_pin_read(self->pin_b); - // logic from the atmel-samd port: provides some damping and scales movement - // down by 4:1. - if (self->quarter >= 4) { - self->position++; - self->quarter = 0; - } else if (self->quarter <= -4) { - self->position--; - self->quarter = 0; - } + shared_module_softencoder_state_update(self, new_state); } -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 +73,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; } @@ -105,12 +93,3 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o self->pin_a = NO_PIN; self->pin_b = NO_PIN; } - -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) { - self->position = new_position; -} diff --git a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h index 1d0fe41839dbb..3693131056851 100644 --- a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h +++ b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.h @@ -35,8 +35,8 @@ typedef struct { mp_obj_base_t base; uint8_t pin_a; uint8_t pin_b; - uint8_t state; - int8_t quarter; + uint8_t state; // + int8_t quarter_count; // count intermediate transitions between detents mp_int_t position; } rotaryio_incrementalencoder_obj_t; diff --git a/ports/nrf/common-hal/rtc/RTC.c b/ports/nrf/common-hal/rtc/RTC.c index 93ba007c83cc1..cdffe094a4b69 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 ea663f897d54a..f827651781f10 --- a/ports/nrf/common-hal/supervisor/Runtime.c +++ b/ports/nrf/common-hal/supervisor/Runtime.c @@ -28,10 +28,10 @@ #include "shared-bindings/supervisor/Runtime.h" #include "supervisor/serial.h" -bool common_hal_get_serial_connected(void) { - return (bool) serial_connected(); +bool common_hal_supervisor_runtime_get_serial_connected(void) { + return (bool)serial_connected(); } -bool common_hal_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); +bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { + return (bool)serial_bytes_available(); } diff --git a/ports/nrf/common-hal/watchdog/WatchDogTimer.c b/ports/nrf/common-hal/watchdog/WatchDogTimer.c index 539b43e762048..3423d3466b0b8 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 8d6df934e4d7a..1ff654c321895 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 614b8c2d32276..81eaa4e329f12 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 ad875dceedd9e..ad608395208ad 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 8e1c360128840..67380303d65dc 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 426a4aa55f789..96818d01c2539 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 c0a7d05a37e67..37daa6c69baaf 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 405f77c4b0221..c70235c4a3947 100644 --- a/ports/nrf/examples/ubluepy_temp.py +++ b/ports/nrf/examples/ubluepy_temp.py @@ -26,6 +26,7 @@ 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 @@ def send_temp(timer_id): 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 2b741f993a8e5..5347af4177adb 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 e64bbc9f52c51..ba05ae1020965 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 3661daa535986..453bc61f2b149 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 6e266e4f7a8ac..7a59531b0e946 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 3ac41a5e47958..99effcea2f97f 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/mpconfigport.mk b/ports/nrf/mpconfigport.mk index 9560064fbc5c4..f349b3665ff3d 100644 --- a/ports/nrf/mpconfigport.mk +++ b/ports/nrf/mpconfigport.mk @@ -11,6 +11,9 @@ INTERNAL_LIBM = 1 USB_SERIAL_NUMBER_LENGTH = 16 +# Number of USB endpoint pairs. +USB_NUM_EP = 8 + # All nRF ports have longints. LONGINT_IMPL = MPZ @@ -37,9 +40,10 @@ CIRCUITPY_RTC ?= 1 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_RGBMATRIX ?= 1 +CIRCUITPY_ROTARYIO_SOFTENCODER = 1 CIRCUITPY_FRAMEBUFFERIO ?= 1 -CIRCUITPY_COUNTIO = 0 +CIRCUITPY_COUNTIO ?= 1 CIRCUITPY_WATCHDOG ?= 1 # nRF52840-specific diff --git a/ports/nrf/mphalport.h b/ports/nrf/mphalport.h index 8bb351401ade4..2b13f82db1129 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 94812d591316a..2c31263c58135 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 9f91b72a14ff3..c54f8e2c13db3 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 269365cc94ff1..aef956f2da82d 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 d64c536bb3843..192a49acca359 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 d64c536bb3843..192a49acca359 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 ce47d73c77323..06a6429227d5b 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 9e144d802a07c..da8080f0afb4f 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 efdc8892a4264..e3f947ca276de 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 fd814968dcbdc..f3a16b7e11bab 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 cf96c6273b14a..0fb529d73b88a 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 b3162e6af922e..2ae490288dac5 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 ca46917205bb7..2999dc774a818 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 8d89d62723a0c..5ce737f6ad4e7 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 93de0b2c498c9..cce48a4c32be1 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 78bb20ce6cf85..9a2acd5cabe62 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 7ca27d56c41cf..1386af7c44e0b 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 b19e9267ccdb3..10bdb2819ac51 100644 --- a/ports/nrf/supervisor/serial.c +++ b/ports/nrf/supervisor/serial.c @@ -28,15 +28,15 @@ #include "supervisor/serial.h" -#if CIRCUITPY_SERIAL_BLE +#if CIRCUITPY_REPL_BLE #include "ble_uart.h" -#elif CIRCUITPY_SERIAL_UART +#elif CIRCUITPY_REPL_UART #include #include "nrf_gpio.h" #include "nrfx_uarte.h" #endif -#if CIRCUITPY_SERIAL_BLE +#if CIRCUITPY_REPL_BLE void serial_init(void) { ble_uart_init(); @@ -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) { @@ -58,7 +58,7 @@ void serial_write(const char *text) { ble_uart_stdout_tx_str(text); } -#elif CIRCUITPY_SERIAL_UART +#elif CIRCUITPY_REPL_UART uint8_t serial_received_char; nrfx_uarte_t serial_instance = NRFX_UARTE_INSTANCE(0); @@ -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,17 +111,17 @@ 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); } } -#endif // CIRCUITPY_SERIAL_UART +#endif // CIRCUITPY_REPL_UART diff --git a/ports/nrf/supervisor/usb.c b/ports/nrf/supervisor/usb.c index 771e86ce03bb5..3ca9b8365dfc2 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/Makefile b/ports/raspberrypi/Makefile index eab7deee68807..2a054516bebae 100644 --- a/ports/raspberrypi/Makefile +++ b/ports/raspberrypi/Makefile @@ -99,13 +99,14 @@ INC += -I. \ -isystem sdk/src/rp2_common/pico_platform/include/ \ -isystem sdk/src/rp2_common/pico_runtime/printf/include/ \ -isystem sdk/src/rp2_common/pico_bootrom/include/ \ + -isystem sdk/src/rp2_common/pico_unique_id/include/ \ -Isdk_config \ -I../../lib/tinyusb/src \ -I../../supervisor/shared/usb \ -I$(BUILD) # Pico specific configuration -CFLAGS += -DPICO_ON_DEVICE=1 -DPICO_NO_BINARY_INFO=0 -DPICO_TIME_DEFAULT_ALARM_POOL_DISABLED=1 -DPICO_DIVIDER_CALL_IDIV0=0 -DPICO_DIVIDER_CALL_LDIV0=0 -DPICO_DIVIDER_HARDWARE=1 -DPICO_DOUBLE_ROM=1 -DPICO_FLOAT_ROM=1 -DPICO_MULTICORE=1 -DPICO_BITS_IN_RAM=0 -DPICO_DIVIDER_IN_RAM=0 -DPICO_DOUBLE_PROPAGATE_NANS=0 -DPICO_DOUBLE_IN_RAM=0 -DPICO_MEM_IN_RAM=0 -DPICO_FLOAT_IN_RAM=0 -DPICO_FLOAT_PROPAGATE_NANS=1 -DPICO_NO_FLASH=0 -DPICO_COPY_TO_RAM=0 -DPICO_DISABLE_SHARED_IRQ_HANDLERS=0 +CFLAGS += -DRASPBERRYPI -DPICO_ON_DEVICE=1 -DPICO_NO_BINARY_INFO=0 -DPICO_TIME_DEFAULT_ALARM_POOL_DISABLED=1 -DPICO_DIVIDER_CALL_IDIV0=0 -DPICO_DIVIDER_CALL_LDIV0=0 -DPICO_DIVIDER_HARDWARE=1 -DPICO_DOUBLE_ROM=1 -DPICO_FLOAT_ROM=1 -DPICO_MULTICORE=1 -DPICO_BITS_IN_RAM=0 -DPICO_DIVIDER_IN_RAM=0 -DPICO_DOUBLE_PROPAGATE_NANS=0 -DPICO_DOUBLE_IN_RAM=0 -DPICO_MEM_IN_RAM=0 -DPICO_FLOAT_IN_RAM=0 -DPICO_FLOAT_PROPAGATE_NANS=1 -DPICO_NO_FLASH=0 -DPICO_COPY_TO_RAM=0 -DPICO_DISABLE_SHARED_IRQ_HANDLERS=0 -DPICO_NO_BI_BOOTSEL_VIA_DOUBLE_RESET=0 OPTIMIZATION_FLAGS ?= -O3 # TinyUSB defines CFLAGS += -DTUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX=1 -DCFG_TUSB_MCU=OPT_MCU_RP2040 -DCFG_TUD_MIDI_RX_BUFSIZE=128 -DCFG_TUD_CDC_RX_BUFSIZE=256 -DCFG_TUD_MIDI_TX_BUFSIZE=128 -DCFG_TUD_CDC_TX_BUFSIZE=256 -DCFG_TUD_MSC_BUFSIZE=1024 @@ -142,20 +143,17 @@ CFLAGS += \ PICO_LDFLAGS = --specs=nosys.specs -Wl,--wrap=__aeabi_ldiv0 -Wl,--wrap=__aeabi_idiv0 -Wl,--wrap=__aeabi_lmul -Wl,--wrap=__clzsi2 -Wl,--wrap=__clzdi2 -Wl,--wrap=__ctzsi2 -Wl,--wrap=__ctzdi2 -Wl,--wrap=__popcountsi2 -Wl,--wrap=__popcountdi2 -Wl,--wrap=__clz -Wl,--wrap=__clzl -Wl,--wrap=__clzll -Wl,--wrap=__aeabi_idiv -Wl,--wrap=__aeabi_idivmod -Wl,--wrap=__aeabi_ldivmod -Wl,--wrap=__aeabi_uidiv -Wl,--wrap=__aeabi_uidivmod -Wl,--wrap=__aeabi_uldivmod -Wl,--wrap=__aeabi_dadd -Wl,--wrap=__aeabi_ddiv -Wl,--wrap=__aeabi_dmul -Wl,--wrap=__aeabi_drsub -Wl,--wrap=__aeabi_dsub -Wl,--wrap=__aeabi_cdcmpeq -Wl,--wrap=__aeabi_cdrcmple -Wl,--wrap=__aeabi_cdcmple -Wl,--wrap=__aeabi_dcmpeq -Wl,--wrap=__aeabi_dcmplt -Wl,--wrap=__aeabi_dcmple -Wl,--wrap=__aeabi_dcmpge -Wl,--wrap=__aeabi_dcmpgt -Wl,--wrap=__aeabi_dcmpun -Wl,--wrap=__aeabi_i2d -Wl,--wrap=__aeabi_l2d -Wl,--wrap=__aeabi_ui2d -Wl,--wrap=__aeabi_ul2d -Wl,--wrap=__aeabi_d2iz -Wl,--wrap=__aeabi_d2lz -Wl,--wrap=__aeabi_d2uiz -Wl,--wrap=__aeabi_d2ulz -Wl,--wrap=__aeabi_d2f -Wl,--wrap=sqrt -Wl,--wrap=cos -Wl,--wrap=sin -Wl,--wrap=tan -Wl,--wrap=atan2 -Wl,--wrap=exp -Wl,--wrap=log -Wl,--wrap=ldexp -Wl,--wrap=copysign -Wl,--wrap=trunc -Wl,--wrap=floor -Wl,--wrap=ceil -Wl,--wrap=round -Wl,--wrap=sincos -Wl,--wrap=asin -Wl,--wrap=acos -Wl,--wrap=atan -Wl,--wrap=sinh -Wl,--wrap=cosh -Wl,--wrap=tanh -Wl,--wrap=asinh -Wl,--wrap=acosh -Wl,--wrap=atanh -Wl,--wrap=exp2 -Wl,--wrap=log2 -Wl,--wrap=exp10 -Wl,--wrap=log10 -Wl,--wrap=pow -Wl,--wrap=powint -Wl,--wrap=hypot -Wl,--wrap=cbrt -Wl,--wrap=fmod -Wl,--wrap=drem -Wl,--wrap=remainder -Wl,--wrap=remquo -Wl,--wrap=expm1 -Wl,--wrap=log1p -Wl,--wrap=fma -Wl,--wrap=__aeabi_fadd -Wl,--wrap=__aeabi_fdiv -Wl,--wrap=__aeabi_fmul -Wl,--wrap=__aeabi_frsub -Wl,--wrap=__aeabi_fsub -Wl,--wrap=__aeabi_cfcmpeq -Wl,--wrap=__aeabi_cfrcmple -Wl,--wrap=__aeabi_cfcmple -Wl,--wrap=__aeabi_fcmpeq -Wl,--wrap=__aeabi_fcmplt -Wl,--wrap=__aeabi_fcmple -Wl,--wrap=__aeabi_fcmpge -Wl,--wrap=__aeabi_fcmpgt -Wl,--wrap=__aeabi_fcmpun -Wl,--wrap=__aeabi_i2f -Wl,--wrap=__aeabi_l2f -Wl,--wrap=__aeabi_ui2f -Wl,--wrap=__aeabi_ul2f -Wl,--wrap=__aeabi_f2iz -Wl,--wrap=__aeabi_f2lz -Wl,--wrap=__aeabi_f2uiz -Wl,--wrap=__aeabi_f2ulz -Wl,--wrap=__aeabi_f2d -Wl,--wrap=sqrtf -Wl,--wrap=cosf -Wl,--wrap=sinf -Wl,--wrap=tanf -Wl,--wrap=atan2f -Wl,--wrap=expf -Wl,--wrap=logf -Wl,--wrap=ldexpf -Wl,--wrap=copysignf -Wl,--wrap=truncf -Wl,--wrap=floorf -Wl,--wrap=ceilf -Wl,--wrap=roundf -Wl,--wrap=sincosf -Wl,--wrap=asinf -Wl,--wrap=acosf -Wl,--wrap=atanf -Wl,--wrap=sinhf -Wl,--wrap=coshf -Wl,--wrap=tanhf -Wl,--wrap=asinhf -Wl,--wrap=acoshf -Wl,--wrap=atanhf -Wl,--wrap=exp2f -Wl,--wrap=log2f -Wl,--wrap=exp10f -Wl,--wrap=log10f -Wl,--wrap=powf -Wl,--wrap=powintf -Wl,--wrap=hypotf -Wl,--wrap=cbrtf -Wl,--wrap=fmodf -Wl,--wrap=dremf -Wl,--wrap=remainderf -Wl,--wrap=remquof -Wl,--wrap=expm1f -Wl,--wrap=log1pf -Wl,--wrap=fmaf -Wl,--wrap=memcpy -Wl,--wrap=memset -Wl,--wrap=__aeabi_memcpy -Wl,--wrap=__aeabi_memset -Wl,--wrap=__aeabi_memcpy4 -Wl,--wrap=__aeabi_memset4 -Wl,--wrap=__aeabi_memcpy8 -Wl,--wrap=__aeabi_memset8 -LDFLAGS = $(CFLAGS) $(PICO_LDFLAGS) -Wl,-T,link.ld -Wl,-Map=$@.map -Wl,-cref -Wl,--gc-sections - # Use toolchain libm if we're not using our own. ifndef INTERNAL_LIBM LIBS += -lm endif -LDFLAGS += -mthumb -mcpu=cortex-m0plus - SRC_SDK := \ src/common/pico_sync/critical_section.c \ src/common/pico_sync/lock_core.c \ src/common/pico_sync/mutex.c \ src/common/pico_time/time.c \ + src/common/pico_time/timeout_helper.c \ src/common/pico_util/pheap.c \ src/rp2_common/hardware_adc/adc.c \ src/rp2_common/hardware_claim/claim.c \ @@ -167,7 +165,7 @@ SRC_SDK := \ src/rp2_common/hardware_irq/irq.c \ src/rp2_common/hardware_pio/pio.c \ src/rp2_common/hardware_pll/pll.c \ - src/rp2_common/hardware_rtc/rtc.c \ + src/rp2_common/hardware_rtc/rtc.c \ src/rp2_common/hardware_spi/spi.c \ src/rp2_common/hardware_sync/sync.c \ src/rp2_common/hardware_timer/timer.c \ @@ -175,6 +173,7 @@ SRC_SDK := \ src/rp2_common/hardware_watchdog/watchdog.c \ src/rp2_common/hardware_xosc/xosc.c \ src/rp2_common/pico_bootrom/bootrom.c \ + src/rp2_common/pico_bootsel_via_double_reset/pico_bootsel_via_double_reset.c \ src/rp2_common/pico_double/double_init_rom.c \ src/rp2_common/pico_fix/rp2040_usb_device_enumeration/rp2040_usb_device_enumeration.c \ src/rp2_common/pico_float/float_init_rom.c \ @@ -184,6 +183,7 @@ SRC_SDK := \ src/rp2_common/pico_printf/printf.c \ src/rp2_common/pico_runtime/runtime.c \ src/rp2_common/pico_stdio/stdio.c \ + src/rp2_common/pico_unique_id/unique_id.c \ SRC_SDK := $(addprefix sdk/, $(SRC_SDK)) @@ -194,8 +194,10 @@ SRC_C += \ bindings/rp2pio/__init__.c \ common-hal/rp2pio/StateMachine.c \ common-hal/rp2pio/__init__.c \ + audio_dma.c \ background.c \ peripherals/pins.c \ + extmod/crypto-algorithms/sha256.c \ fatfs_port.c \ lib/libc/string0.c \ lib/mp-readline/readline.c \ @@ -227,8 +229,8 @@ SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) SRC_S = supervisor/$(CHIP_FAMILY)_cpu.s -SRC_S_UPPER = bs2_default_padded_checksummed.S \ - sdk/src/rp2_common/hardware_divider/divider.S \ +BOOT2_S_CFLAGS ?= -DPICO_FLASH_SPI_CLKDIV=4 +SRC_S_UPPER = sdk/src/rp2_common/hardware_divider/divider.S \ sdk/src/rp2_common/hardware_irq/irq_handler_chain.S \ sdk/src/rp2_common/pico_bit_ops/bit_ops_aeabi.S \ sdk/src/rp2_common/pico_double/double_aeabi.S \ @@ -249,7 +251,29 @@ endif OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_S_UPPER:.S=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) +OBJ += $(BUILD)/boot2_padded_checksummed.o + +$(BUILD)/boot2_padded_checksummed.o: $(BUILD)/boot2_padded_checksummed.S + $(STEPECHO) "CC $<" + $(Q)$(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD)/boot2_padded_checksummed.S: $(BUILD)/boot2.bin + $(STEPECHO) "PAD_CHECKSUM $<" + $(Q)$(PYTHON3) sdk/src/rp2_common/boot_stage2/pad_checksum -s 0xffffffff $< $@ + +$(BUILD)/boot2.bin: $(BUILD)/boot2.elf + $(STEPECHO) "OBJCOPY $<" + $(Q)$(OBJCOPY) -O binary $< $@ + + +$(BUILD)/stage2.c: stage2.c.jinja gen_stage2.py | $(BUILD)/ + $(STEPECHO) "GEN $<" + $(Q)$(PYTHON3) gen_stage2.py $< $@ $(EXTERNAL_FLASH_DEVICES) +$(BUILD)/boot2.elf: $(BUILD)/stage2.c + $(STEPECHO) "BOOT $<" + $(Q)$(CC) $(CFLAGS) $(BOOT2_S_CFLAGS) -Os -ggdb3 -I. -fPIC --specs=nosys.specs -nostartfiles -Wl,-T,boot_stage2.ld -Wl,-Map=$@.map -o $@ $< + $(Q)$(SIZE) $@ SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) @@ -257,12 +281,14 @@ all: $(BUILD)/firmware.uf2 $(BUILD)/firmware.elf: $(OBJ) link.ld $(STEPECHO) "LINK $@" - $(Q)$(CC) -o $@ $(LDFLAGS) $(OBJ) + $(Q)echo $(OBJ) > $(BUILD)/firmware.objs + $(Q)echo $(PICO_LDFLAGS) > $(BUILD)/firmware.ldflags + $(Q)$(CC) -o $@ $(CFLAGS) @$(BUILD)/firmware.ldflags -Wl,-T,link.ld -Wl,-Map=$@.map -Wl,-cref -Wl,--gc-sections @$(BUILD)/firmware.objs $(Q)$(SIZE) $@ | $(PYTHON3) $(TOP)/tools/build_memory_info.py link.ld $(BUILD)/firmware.bin: $(BUILD)/firmware.elf $(STEPECHO) "Create $@" - $(Q)$(OBJCOPY) -O binary $^ $@ + $(Q)$(OBJCOPY) -O binary -R .dtcm_bss $^ $@ $(BUILD)/firmware.uf2: $(BUILD)/firmware.bin $(STEPECHO) "Create $@" diff --git a/ports/raspberrypi/audio_dma.c b/ports/raspberrypi/audio_dma.c new file mode 100644 index 0000000000000..28a80a770c8bb --- /dev/null +++ b/ports/raspberrypi/audio_dma.c @@ -0,0 +1,400 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "audio_dma.h" + +#include "shared-bindings/audiocore/RawSample.h" +#include "shared-bindings/audiocore/WaveFile.h" +#include "supervisor/background_callback.h" + +#include "py/mpstate.h" +#include "py/runtime.h" + +#include "src/rp2_common/hardware_irq/include/hardware/irq.h" + +#if CIRCUITPY_AUDIOPWMIO || CIRCUITPY_AUDIOBUSIO + +#define AUDIO_DMA_CHANNEL_COUNT NUM_DMA_CHANNELS + +void audio_dma_reset(void) { + for (size_t channel = 0; channel < AUDIO_DMA_CHANNEL_COUNT; channel++) { + if (MP_STATE_PORT(playing_audio)[channel] == NULL) { + continue; + } + + audio_dma_stop(MP_STATE_PORT(playing_audio)[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) { + if (dma->first_buffer_free) { + *output_buffer = dma->first_buffer; + } else { + *output_buffer = dma->second_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)) { + *output_buffer_length = buffer_length / dma->sample_spacing; + uint32_t out_i = 0; + if (dma->sample_resolution <= 8 && dma->output_resolution > 8) { + size_t shift = dma->output_resolution - dma->sample_resolution; + + 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; + } else if (dma->unsigned_to_signed) { + ((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; + } + 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; + } else if (dma->unsigned_to_signed) { + ((int8_t *)*output_buffer)[out_i] = ((uint8_t *)buffer)[i] - 0x80; + } else { + ((uint8_t *)*output_buffer)[out_i] = ((uint8_t *)buffer)[i]; + } + out_i += 1; + } + } else if (dma->sample_resolution > 8 && dma->output_resolution > 8) { + 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; + } else { + ((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; + } else { + ((uint16_t *)*output_buffer)[out_i] = ((uint16_t *)*output_buffer)[out_i] >> shift; + } + } + out_i += 1; + } + } + } else { + *output_buffer = buffer; + *output_buffer_length = buffer_length; + } + #pragma GCC diagnostic pop + dma->first_buffer_free = !dma->first_buffer_free; +} + +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; + uint32_t output_buffer_length; + audioio_get_buffer_result_t get_buffer_result; + uint8_t *buffer; + uint32_t buffer_length; + get_buffer_result = audiosample_get_buffer(dma->sample, + dma->single_channel, dma->audio_channel, &buffer, &buffer_length); + + if (get_buffer_result == GET_BUFFER_ERROR) { + audio_dma_stop(dma); + return; + } + + audio_dma_convert_signed(dma, buffer, buffer_length, &output_buffer, &output_buffer_length); + + // If we don't have an output buffer, save the pointer to first_buffer for use in the single + // buffer special case. + if (dma->first_buffer == NULL) { + dma->first_buffer = output_buffer; + } + + dma_channel_set_trans_count(dma_channel, output_buffer_length / dma->output_size, false /* trigger */); + dma_channel_set_read_addr(dma_channel, output_buffer, false /* trigger */); + if (get_buffer_result == GET_BUFFER_DONE) { + if (dma->loop) { + 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]; + 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) { + // 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); + dma->channel[1] = dma_claim_unused_channel(false); + if (dma->channel[0] == NUM_DMA_CHANNELS || dma->channel[1] == NUM_DMA_CHANNELS) { + if (dma->channel[0] < NUM_DMA_CHANNELS) { + dma_channel_unclaim(dma->channel[0]); + } + return AUDIO_DMA_DMA_BUSY; + } + + dma->sample = sample; + dma->loop = loop; + dma->single_channel = single_channel; + dma->audio_channel = audio_channel; + dma->signed_to_unsigned = false; + dma->unsigned_to_signed = false; + dma->output_signed = output_signed; + dma->sample_spacing = 1; + dma->first_channel_free = true; + dma->output_resolution = output_resolution; + dma->sample_resolution = audiosample_bits_per_sample(sample); + audiosample_reset_buffer(sample, single_channel, audio_channel); + + bool single_buffer; + 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); + + // 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)) { + max_buffer_length /= dma->sample_spacing; + 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); + if (dma->second_buffer == NULL) { + return AUDIO_DMA_MEMORY_ERROR; + } + } + dma->signed_to_unsigned = !output_signed && samples_signed; + dma->unsigned_to_signed = output_signed && !samples_signed; + } + + if (output_resolution > 8) { + dma->output_size = 2; + } else { + dma->output_size = 1; + } + // Transfer both channels at once. + if (!single_channel && audiosample_channel_count(sample) == 2) { + dma->output_size *= 2; + } + + enum dma_channel_transfer_size dma_size = DMA_SIZE_8; + if (dma->output_size == 2) { + dma_size = DMA_SIZE_16; + } else if (dma->output_size == 4) { + dma_size = DMA_SIZE_32; + } + + for (size_t i = 0; i < 2; i++) { + dma_channel_config c = dma_channel_get_default_config(dma->channel[i]); + channel_config_set_transfer_data_size(&c, dma_size); + channel_config_set_dreq(&c, dma_trigger_source); + channel_config_set_read_increment(&c, true); + channel_config_set_write_increment(&c, false); + // 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 */); + } + + // We keep the audio_dma_t for internal use and the sample as a root pointer because it + // contains the audiodma structure. + MP_STATE_PORT(playing_audio)[dma->channel[0]] = dma; + MP_STATE_PORT(playing_audio)[dma->channel[1]] = dma; + + // Load the first two blocks up front. + audio_dma_load_next_block(dma); + if (!single_buffer) { + audio_dma_load_next_block(dma); + } + + // Special case the DMA for a single buffer. It's commonly used for a single wave length of sound + // and may be short. Therefore, we use DMA chaining to loop quickly without involving interrupts. + // On the RP2040 we chain by having a second DMA writing to the config registers of the first. + // Read and write addresses change with DMA so we need to reset the read address back to the + // start of the sample. + if (single_buffer) { + dma_channel_config c = dma_channel_get_default_config(dma->channel[1]); + channel_config_set_transfer_data_size(&c, DMA_SIZE_32); + channel_config_set_dreq(&c, 0x3f); // dma as fast as possible + channel_config_set_read_increment(&c, false); + channel_config_set_write_increment(&c, false); + channel_config_set_chain_to(&c, dma->channel[1]); // Chain to ourselves so we stop. + dma_channel_configure(dma->channel[1], &c, + &dma_hw->ch[dma->channel[0]].al3_read_addr_trig, // write address + &dma->first_buffer, // read address + 1, // transaction count + false); // trigger + } else { + // Enable our DMA channels on DMA0 to the CPU. This will wake us up when + // we're WFI. + dma_hw->inte0 |= (1 << dma->channel[0]) | (1 << dma->channel[1]); + irq_set_mask_enabled(1 << DMA_IRQ_0, true); + } + + dma_channel_start(dma->channel[0]); + + return AUDIO_DMA_OK; +} + +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); + + // Run any remaining audio tasks because we remove ourselves from + // playing_audio. + RUN_BACKGROUND_TASKS; + + for (size_t i = 0; i < 2; i++) { + size_t channel = dma->channel[i]; + + dma_channel_config c = dma_channel_get_default_config(dma->channel[i]); + channel_config_set_enable(&c, false); + dma_channel_set_config(channel, &c, false /* trigger */); + + if (dma_channel_is_busy(channel)) { + dma_channel_abort(channel); + } + dma_channel_set_read_addr(channel, NULL, false /* trigger */); + dma_channel_set_write_addr(channel, NULL, false /* trigger */); + dma_channel_set_trans_count(channel, 0, false /* trigger */); + dma_channel_unclaim(channel); + MP_STATE_PORT(playing_audio)[channel] = NULL; + dma->channel[i] = NUM_DMA_CHANNELS; + } + + // Hold onto our buffers. +} + +// 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) { + 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) { + // 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; + size_t second = 1; + if (dma_channel_is_busy(dma->channel[0])) { + first = 1; + second = 0; + } + dma_hw->ch[dma->channel[first]].al1_ctrl |= DMA_CH0_CTRL_TRIG_EN_BITS; + dma_hw->ch[dma->channel[second]].al1_ctrl |= DMA_CH0_CTRL_TRIG_EN_BITS; +} + +bool audio_dma_get_paused(audio_dma_t *dma) { + if (dma->channel[0] >= AUDIO_DMA_CHANNEL_COUNT) { + return false; + } + uint32_t control = dma_hw->ch[dma->channel[0]].ctrl_trig; + + return (control & DMA_CH0_CTRL_TRIG_EN_BITS) == 0; +} + +void audio_dma_init(audio_dma_t *dma) { + dma->first_buffer = NULL; + dma->second_buffer = NULL; +} + +void audio_dma_deinit(audio_dma_t *dma) { + m_free(dma->first_buffer); + dma->first_buffer = NULL; + + m_free(dma->second_buffer); + dma->second_buffer = NULL; +} + +bool audio_dma_get_playing(audio_dma_t *dma) { + if (dma->channel[0] == NUM_DMA_CHANNELS) { + return false; + } + if (!dma_channel_is_busy(dma->channel[0]) && + !dma_channel_is_busy(dma->channel[1])) { + audio_dma_stop(dma); + return false; + } + + return true; +} + +// 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; + if (dma == NULL) { + return; + } + + audio_dma_load_next_block(dma); +} + +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); + dma_hw->ints0 = mask; + } + } +} + +#endif diff --git a/ports/raspberrypi/audio_dma.h b/ports/raspberrypi/audio_dma.h new file mode 100644 index 0000000000000..faececa8dff82 --- /dev/null +++ b/ports/raspberrypi/audio_dma.h @@ -0,0 +1,91 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_RASPBERRYPI_AUDIO_DMA_OUT_H +#define MICROPY_INCLUDED_RASPBERRYPI_AUDIO_DMA_OUT_H + +#include "py/obj.h" +#include "supervisor/background_callback.h" + +#include "src/rp2_common/hardware_dma/include/hardware/dma.h" + +typedef struct { + mp_obj_t sample; + uint8_t channel[2]; + uint8_t audio_channel; + uint8_t output_size; + uint8_t sample_spacing; + bool loop; + bool single_channel; + bool signed_to_unsigned; + bool unsigned_to_signed; + bool output_signed; + bool first_channel_free; + bool first_buffer_free; + uint8_t output_resolution; // in bits + uint8_t sample_resolution; // in bits + uint8_t *first_buffer; + uint8_t *second_buffer; + background_callback_t callback; +} audio_dma_t; + +typedef enum { + AUDIO_DMA_OK, + AUDIO_DMA_DMA_BUSY, + AUDIO_DMA_MEMORY_ERROR, +} audio_dma_result; + + +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. +// Sample is the python object for the sample to play. +// loop is true if we should loop the sample. +// single_channel is true if we only output a single channel. When false, all channels will be +// output. +// audio_channel is the index of the channel to dma. single_channel must be false in this case. +// 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); + +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 c85b83b41ed94..4b5190aa2740c 100644 --- a/ports/raspberrypi/background.c +++ b/ports/raspberrypi/background.c @@ -25,20 +25,13 @@ */ #include "background.h" -#include "supervisor/filesystem.h" -#include "supervisor/shared/tick.h" -#include "supervisor/usb.h" - #include "py/runtime.h" -#include "shared-module/network/__init__.h" -#include "supervisor/shared/stack.h" #include "supervisor/port.h" -#if CIRCUITPY_DISPLAYIO -#include "shared-module/displayio/__init__.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) {} +void port_background_task(void) { +} diff --git a/ports/raspberrypi/bindings/rp2pio/StateMachine.c b/ports/raspberrypi/bindings/rp2pio/StateMachine.c index 0f6f84a565744..b85ee5d2d4f84 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.c +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.c @@ -36,6 +36,7 @@ #include "lib/utils/buffer_helper.h" #include "lib/utils/context_manager_helpers.h" #include "lib/utils/interrupt_char.h" +#include "py/binary.h" #include "py/mperrno.h" #include "py/objproperty.h" #include "py/runtime.h" @@ -54,8 +55,7 @@ //| This class is designed to facilitate sharing of PIO resources. By default, //| it is assumed that the state machine is used on its own and can be placed //| in either PIO. State machines with the same program will be placed in the -//| same PIO if possible. To ensure multiple state machines share a PIO use -//| the ``colocate`` kwarg during construction and create them one after another.""" +//| same PIO if possible.""" //| //| def __init__(self, //| program: ReadableBuffer, @@ -64,20 +64,28 @@ //| init: Optional[ReadableBuffer] = None, //| first_out_pin: Optional[microcontroller.Pin] = None, //| out_pin_count: int = 1, +//| initial_out_pin_state: int = 0, +//| initial_out_pin_direction: int = 0xffffffff, //| first_in_pin: Optional[microcontroller.Pin] = None, //| in_pin_count: int = 1, +//| pull_in_pin_up: int = 0, +//| pull_in_pin_down: int = 0, //| first_set_pin: Optional[microcontroller.Pin] = None, //| set_pin_count: int = 1, +//| initial_set_pin_state: int = 0, +//| initial_set_pin_direction: int = 0x1f, //| first_sideset_pin: Optional[microcontroller.Pin] = None, //| sideset_pin_count: int = 1, +//| initial_sideset_pin_state: int = 0, +//| initial_sideset_pin_direction: int = 0x1f, //| exclusive_pin_use: bool = True, //| auto_pull: bool = False, //| pull_threshold : int = 32, //| out_shift_right : bool = True, +//| wait_for_txstall: bool = True, //| auto_push: bool = False, //| push_threshold : int = 32, //| in_shift_right : bool = True) -> None: -// //| colocate: Union[int, StateMachine, None] = None //| //| """Construct a StateMachine object on the given pins with the given program. //| @@ -87,12 +95,20 @@ //| is started so instructions may be intermingled //| :param ~microcontroller.Pin first_out_pin: the first pin to use with the OUT instruction //| :param int out_pin_count: the count of consecutive pins to use with OUT starting at first_out_pin +//| :param int initial_out_pin_state: the initial output value for out pins starting at first_out_pin +//| :param int initial_out_pin_direction: the initial output direction for out pins starting at first_out_pin //| :param ~microcontroller.Pin first_in_pin: the first pin to use with the IN instruction //| :param int in_pin_count: the count of consecutive pins to use with IN starting at first_in_pin +//| :param int pull_in_pin_up: a 1-bit in this mask sets pull up on the corresponding in pin +//| :param int pull_in_pin_down: a 1-bit in this mask sets pull up on the corresponding in pin. Setting both pulls enables a "bus keep" function, i.e. a weak pull to whatever is current high/low state of GPIO. //| :param ~microcontroller.Pin first_set_pin: the first pin to use with the SET instruction //| :param int set_pin_count: the count of consecutive pins to use with SET starting at first_set_pin +//| :param int initial_set_pin_state: the initial output value for set pins starting at first_set_pin +//| :param int initial_set_pin_direction: the initial output direction for set pins starting at first_set_pin //| :param ~microcontroller.Pin first_sideset_pin: the first pin to use with a side set //| :param int sideset_pin_count: the count of consecutive pins to use with a side set starting at first_sideset_pin +//| :param int initial_sideset_pin_state: the initial output value for sideset pins starting at first_sideset_pin +//| :param int initial_sideset_pin_direction: the initial output direction for sideset pins starting at first_sideset_pin //| :param bool exclusive_pin_use: When True, do not share any pins with other state machines. Pins are never shared with other peripherals //| :param bool auto_pull: When True, automatically load data from the tx FIFO into the //| output shift register (OSR) when an OUT instruction shifts more than pull_threshold bits @@ -100,6 +116,10 @@ //| :param bool out_shift_right: When True, data is shifted out the right side (LSB) of the //| OSR. It is shifted out the left (MSB) otherwise. NOTE! This impacts data alignment //| when the number of bytes is not a power of two (1, 2 or 4 bytes). +//| :param bool wait_for_txstall: When True, writing data out will block until the TX FIFO and OSR are empty +//| and an instruction is stalled waiting for more data. When False, data writes won't +//| wait for the OSR to empty (only the TX FIFO) so make sure you give enough time before +//| deiniting or stopping the state machine. //| :param bool auto_push: When True, automatically save data from input shift register //| (ISR) into the rx FIFO when an IN instruction shifts more than push_threshold bits //| :param int push_threshold: Number of bits to shift before saving the ISR value to the RX FIFO @@ -113,29 +133,45 @@ STATIC mp_obj_t rp2pio_statemachine_make_new(const mp_obj_type_t *type, size_t n rp2pio_statemachine_obj_t *self = m_new_obj(rp2pio_statemachine_obj_t); self->base.type = &rp2pio_statemachine_type; enum { ARG_program, ARG_frequency, ARG_init, - ARG_first_out_pin, ARG_out_pin_count, + ARG_first_out_pin, ARG_out_pin_count, ARG_initial_out_pin_state, ARG_initial_out_pin_direction, ARG_first_in_pin, ARG_in_pin_count, - ARG_first_set_pin, ARG_set_pin_count, - ARG_first_sideset_pin, ARG_sideset_pin_count, + ARG_pull_in_pin_up, ARG_pull_in_pin_down, + ARG_first_set_pin, ARG_set_pin_count, ARG_initial_set_pin_state, ARG_initial_set_pin_direction, + ARG_first_sideset_pin, ARG_sideset_pin_count, ARG_initial_sideset_pin_state, ARG_initial_sideset_pin_direction, ARG_exclusive_pin_use, ARG_auto_pull, ARG_pull_threshold, ARG_out_shift_right, + ARG_wait_for_txstall, ARG_auto_push, ARG_push_threshold, ARG_in_shift_right}; static const mp_arg_t allowed_args[] = { { MP_QSTR_program, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_frequency, MP_ARG_REQUIRED | MP_ARG_INT }, { MP_QSTR_init, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_first_out_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_out_pin_count, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_initial_out_pin_state, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_initial_out_pin_direction, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} }, + { MP_QSTR_first_in_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_in_pin_count, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_pull_in_pin_up, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_pull_in_pin_down, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_first_set_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_set_pin_count, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_initial_set_pin_state, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_initial_set_pin_direction, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0x1f} }, + { MP_QSTR_first_sideset_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_sideset_pin_count, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_initial_sideset_pin_state, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_initial_sideset_pin_direction, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0x1f} }, + { MP_QSTR_exclusive_pin_use, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, { MP_QSTR_auto_pull, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, { MP_QSTR_pull_threshold, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 32} }, { MP_QSTR_out_shift_right, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_wait_for_txstall, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, { MP_QSTR_auto_push, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, { MP_QSTR_push_threshold, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 32} }, { MP_QSTR_in_shift_right, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, @@ -189,7 +225,7 @@ STATIC mp_obj_t rp2pio_statemachine_make_new(const mp_obj_type_t *type, size_t n if (bufinfo.len % 2 != 0) { mp_raise_ValueError(translate("Program size invalid")); } - if (bufinfo.len > 32) { + if (bufinfo.len > 64) { mp_raise_ValueError(translate("Program too large")); } @@ -201,12 +237,14 @@ STATIC mp_obj_t rp2pio_statemachine_make_new(const mp_obj_type_t *type, size_t n bufinfo.buf, bufinfo.len / 2, args[ARG_frequency].u_int, init_bufinfo.buf, init_bufinfo.len / 2, - first_out_pin, args[ARG_out_pin_count].u_int, - first_in_pin, args[ARG_in_pin_count].u_int, - first_set_pin, args[ARG_set_pin_count].u_int, - first_sideset_pin, args[ARG_sideset_pin_count].u_int, + first_out_pin, args[ARG_out_pin_count].u_int, args[ARG_initial_out_pin_state].u_int, args[ARG_initial_out_pin_direction].u_int, + first_in_pin, args[ARG_in_pin_count].u_int, args[ARG_pull_in_pin_up].u_int, args[ARG_pull_in_pin_down].u_int, + first_set_pin, args[ARG_set_pin_count].u_int, args[ARG_initial_set_pin_state].u_int, args[ARG_initial_set_pin_direction].u_int, + first_sideset_pin, args[ARG_sideset_pin_count].u_int, args[ARG_initial_sideset_pin_state].u_int, args[ARG_initial_sideset_pin_direction].u_int, + 0, args[ARG_exclusive_pin_use].u_bool, args[ARG_auto_pull].u_bool, pull_threshold, args[ARG_out_shift_right].u_bool, + args[ARG_wait_for_txstall].u_bool, args[ARG_auto_push].u_bool, push_threshold, args[ARG_in_shift_right].u_bool); return MP_OBJ_FROM_PTR(self); } @@ -247,11 +285,53 @@ STATIC void check_for_deinit(rp2pio_statemachine_obj_t *self) { } } -// // | def restart(self, *other_state_machines) -> None: -// // | """Restarts this state machine and any others given. They must share -// // | an underlying PIO. An exception will be raised otherwise.""" -// // | ... -// // | +//| def restart(self) -> None: +//| """Resets this state machine, runs any init and enables the clock.""" +// TODO: "and any others given. They must share an underlying PIO. An exception will be raised otherwise."" +//| ... +//| +STATIC mp_obj_t rp2pio_statemachine_restart(mp_obj_t self_obj) { + rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(self_obj); + check_for_deinit(self); + + common_hal_rp2pio_statemachine_restart(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(rp2pio_statemachine_restart_obj, rp2pio_statemachine_restart); + + +//| def run(self, instructions: ReadableBuffer) -> None: +//| """Runs all given instructions. They will likely be interleaved with +//| in-memory instructions. Make sure this doesn't wait for input! +//| +//| This can be used to output internal state to the RX FIFO and then +//| read with `readinto`.""" +//| ... +//| +STATIC mp_obj_t rp2pio_statemachine_run(mp_obj_t self_obj, mp_obj_t instruction_obj) { + rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(self_obj); + check_for_deinit(self); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(instruction_obj, &bufinfo, MP_BUFFER_READ); + + common_hal_rp2pio_statemachine_run(self, bufinfo.buf, bufinfo.len); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(rp2pio_statemachine_run_obj, rp2pio_statemachine_run); + +//| def stop(self) -> None: +//| """Stops the state machine clock. Use `restart` to enable it.""" +//| ... +//| +STATIC mp_obj_t rp2pio_statemachine_stop(mp_obj_t self_obj) { + rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(self_obj); + check_for_deinit(self); + + common_hal_rp2pio_statemachine_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(rp2pio_statemachine_stop_obj, rp2pio_statemachine_stop); //| def write(self, buffer: ReadableBuffer, *, start: int = 0, end: Optional[int] = None) -> None: //| """Write the data contained in ``buffer`` to the state machine. If the buffer is empty, nothing happens. @@ -261,7 +341,6 @@ STATIC void check_for_deinit(rp2pio_statemachine_obj_t *self) { //| :param int end: End of the slice; this index is not included. Defaults to ``len(buffer)``""" //| ... //| - STATIC mp_obj_t rp2pio_statemachine_write(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_buffer, ARG_start, ARG_end }; static const mp_arg_t allowed_args[] = { @@ -279,12 +358,17 @@ STATIC mp_obj_t rp2pio_statemachine_write(size_t n_args, const mp_obj_t *pos_arg int32_t start = args[ARG_start].u_int; size_t length = bufinfo.len; normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); - if (length == 0) { return mp_const_none; } - bool ok = common_hal_rp2pio_statemachine_write(self, ((uint8_t*)bufinfo.buf) + start, length); + 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); if (mp_hal_is_interrupted()) { return mp_const_none; } @@ -296,110 +380,132 @@ STATIC mp_obj_t rp2pio_statemachine_write(size_t n_args, const mp_obj_t *pos_arg MP_DEFINE_CONST_FUN_OBJ_KW(rp2pio_statemachine_write_obj, 2, rp2pio_statemachine_write); -// // | def readinto(self, buffer: WriteableBuffer, *, start: int = 0, end: Optional[int] = None) -> None: -// // | """Read into ``buffer``. If the number of bytes to read is 0, nothing happens. -// // | -// // | :param ~_typing.WriteableBuffer buffer: Read data into this buffer -// // | :param int start: Start of the slice of ``buffer`` to read into: ``buffer[start:end]`` -// // | :param int end: End of the slice; this index is not included. Defaults to ``len(buffer)`` -// // | :param int write_value: Value to write while reading. (Usually ignored.)""" -// // | ... -// // | - -// STATIC mp_obj_t rp2pio_statemachine_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { -// enum { ARG_buffer, ARG_start, ARG_end, ARG_write_value }; -// static const mp_arg_t allowed_args[] = { -// { MP_QSTR_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -// { MP_QSTR_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, -// { MP_QSTR_end, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MAX} }, -// { MP_QSTR_write_value,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, -// }; -// rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); -// check_for_deinit(self); -// check_lock(self); -// 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); - -// mp_buffer_info_t bufinfo; -// mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); -// int32_t start = args[ARG_start].u_int; -// size_t length = bufinfo.len; -// normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); - -// if (length == 0) { -// return mp_const_none; -// } - -// bool ok = common_hal_rp2pio_statemachine_read(self, ((uint8_t*)bufinfo.buf) + start, length, args[ARG_write_value].u_int); -// if (!ok) { -// mp_raise_OSError(MP_EIO); -// } -// return mp_const_none; -// } -// MP_DEFINE_CONST_FUN_OBJ_KW(rp2pio_statemachine_readinto_obj, 2, rp2pio_statemachine_readinto); - -// //| def write_readinto(self, buffer_out: ReadableBuffer, buffer_in: WriteableBuffer, *, out_start: int = 0, out_end: Optional[int] = None, in_start: int = 0, in_end: Optional[int] = None) -> None: -// //| """Write out the data in ``buffer_out`` while simultaneously reading data into ``buffer_in``. -// //| The SPI object must be locked. -// //| The lengths of the slices defined by ``buffer_out[out_start:out_end]`` and ``buffer_in[in_start:in_end]`` -// //| must be equal. -// //| If buffer slice lengths are both 0, nothing happens. -// //| -// //| :param ~_typing.ReadableBuffer buffer_out: Write out the data in this buffer -// //| :param ~_typing.WriteableBuffer buffer_in: Read data into this buffer -// //| :param int out_start: Start of the slice of buffer_out to write out: ``buffer_out[out_start:out_end]`` -// //| :param int out_end: End of the slice; this index is not included. Defaults to ``len(buffer_out)`` -// //| :param int in_start: Start of the slice of ``buffer_in`` to read into: ``buffer_in[in_start:in_end]`` -// //| :param int in_end: End of the slice; this index is not included. Defaults to ``len(buffer_in)``""" -// //| ... -// //| - -// STATIC mp_obj_t rp2pio_statemachine_write_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { -// enum { ARG_buffer_out, ARG_buffer_in, ARG_out_start, ARG_out_end, ARG_in_start, ARG_in_end }; -// static const mp_arg_t allowed_args[] = { -// { MP_QSTR_buffer_out, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -// { MP_QSTR_buffer_in, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -// { MP_QSTR_out_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, -// { MP_QSTR_out_end, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MAX} }, -// { MP_QSTR_in_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, -// { MP_QSTR_in_end, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MAX} }, -// }; -// rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); -// check_for_deinit(self); -// check_lock(self); -// 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); - -// mp_buffer_info_t buf_out_info; -// mp_get_buffer_raise(args[ARG_buffer_out].u_obj, &buf_out_info, MP_BUFFER_READ); -// int32_t out_start = args[ARG_out_start].u_int; -// size_t out_length = buf_out_info.len; -// normalize_buffer_bounds(&out_start, args[ARG_out_end].u_int, &out_length); - -// mp_buffer_info_t buf_in_info; -// mp_get_buffer_raise(args[ARG_buffer_in].u_obj, &buf_in_info, MP_BUFFER_WRITE); -// int32_t in_start = args[ARG_in_start].u_int; -// size_t in_length = buf_in_info.len; -// normalize_buffer_bounds(&in_start, args[ARG_in_end].u_int, &in_length); - -// if (out_length != in_length) { -// mp_raise_ValueError(translate("buffer slices must be of equal length")); -// } - -// if (out_length == 0) { -// return mp_const_none; -// } - -// bool ok = common_hal_rp2pio_statemachine_transfer(self, -// ((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); -// } -// return mp_const_none; -// } -// MP_DEFINE_CONST_FUN_OBJ_KW(rp2pio_statemachine_write_readinto_obj, 2, rp2pio_statemachine_write_readinto); +//| def readinto(self, buffer: WriteableBuffer, *, start: int = 0, end: Optional[int] = None) -> None: +//| """Read into ``buffer``. If the number of bytes to read is 0, nothing happens. The buffer +//| include any data added to the fifo even if it was added before this was called. +//| +//| :param ~_typing.WriteableBuffer buffer: Read data into this buffer +//| :param int start: Start of the slice of ``buffer`` to read into: ``buffer[start:end]`` +//| :param int end: End of the slice; this index is not included. Defaults to ``len(buffer)``""" +//| ... +//| + +STATIC mp_obj_t rp2pio_statemachine_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_buffer, ARG_start, ARG_end }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_end, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MAX} }, + }; + rp2pio_statemachine_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_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); + int32_t start = args[ARG_start].u_int; + size_t length = bufinfo.len; + normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); + + if (length == 0) { + return mp_const_none; + } + + 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); + if (!ok) { + mp_raise_OSError(MP_EIO); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(rp2pio_statemachine_readinto_obj, 2, rp2pio_statemachine_readinto); + +//| def write_readinto(self, buffer_out: ReadableBuffer, buffer_in: WriteableBuffer, *, out_start: int = 0, out_end: Optional[int] = None, in_start: int = 0, in_end: Optional[int] = None) -> None: +//| """Write out the data in ``buffer_out`` while simultaneously reading data into ``buffer_in``. +//| The lengths of the slices defined by ``buffer_out[out_start:out_end]`` and ``buffer_in[in_start:in_end]`` +//| may be different. The function will return once both are filled. +//| If buffer slice lengths are both 0, nothing happens. +//| +//| :param ~_typing.ReadableBuffer buffer_out: Write out the data in this buffer +//| :param ~_typing.WriteableBuffer buffer_in: Read data into this buffer +//| :param int out_start: Start of the slice of buffer_out to write out: ``buffer_out[out_start:out_end]`` +//| :param int out_end: End of the slice; this index is not included. Defaults to ``len(buffer_out)`` +//| :param int in_start: Start of the slice of ``buffer_in`` to read into: ``buffer_in[in_start:in_end]`` +//| :param int in_end: End of the slice; this index is not included. Defaults to ``len(buffer_in)``""" +//| ... +//| + +STATIC mp_obj_t rp2pio_statemachine_write_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_buffer_out, ARG_buffer_in, ARG_out_start, ARG_out_end, ARG_in_start, ARG_in_end }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_buffer_out, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_buffer_in, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_out_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_out_end, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MAX} }, + { MP_QSTR_in_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_in_end, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MAX} }, + }; + rp2pio_statemachine_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_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_buffer_info_t buf_out_info; + mp_get_buffer_raise(args[ARG_buffer_out].u_obj, &buf_out_info, MP_BUFFER_READ); + int32_t out_start = args[ARG_out_start].u_int; + size_t out_length = buf_out_info.len; + normalize_buffer_bounds(&out_start, args[ARG_out_end].u_int, &out_length); + + mp_buffer_info_t buf_in_info; + mp_get_buffer_raise(args[ARG_buffer_in].u_obj, &buf_in_info, MP_BUFFER_WRITE); + int32_t in_start = args[ARG_in_start].u_int; + size_t in_length = buf_in_info.len; + normalize_buffer_bounds(&in_start, args[ARG_in_end].u_int, &in_length); + + if (out_length == 0 && in_length == 0) { + return mp_const_none; + } + + int in_stride_in_bytes = mp_binary_get_size('@', buf_in_info.typecode, NULL); + if (in_stride_in_bytes > 4) { + mp_raise_ValueError(translate("In-buffer elements must be <= 4 bytes long")); + } + + int out_stride_in_bytes = mp_binary_get_size('@', buf_out_info.typecode, NULL); + if (out_stride_in_bytes > 4) { + mp_raise_ValueError(translate("Out-buffer elements must be <= 4 bytes long")); + } + + 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); + if (!ok) { + mp_raise_OSError(MP_EIO); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(rp2pio_statemachine_write_readinto_obj, 2, rp2pio_statemachine_write_readinto); + +//| def clear_rxfifo(self) -> None: +//| """Clears any unread bytes in the rxfifo.""" +//| ... +//| +STATIC mp_obj_t rp2pio_statemachine_obj_clear_rxfifo(mp_obj_t self_in) { + rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_rp2pio_statemachine_clear_rxfifo(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(rp2pio_statemachine_clear_rxfifo_obj, rp2pio_statemachine_obj_clear_rxfifo); //| frequency: int //| """The actual state machine frequency. This may not match the frequency requested @@ -413,9 +519,55 @@ STATIC mp_obj_t rp2pio_statemachine_obj_get_frequency(mp_obj_t self_in) { } MP_DEFINE_CONST_FUN_OBJ_1(rp2pio_statemachine_get_frequency_obj, rp2pio_statemachine_obj_get_frequency); +STATIC mp_obj_t rp2pio_statemachine_obj_set_frequency(mp_obj_t self_in, mp_obj_t frequency) { + rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + common_hal_rp2pio_statemachine_set_frequency(self, mp_obj_get_int(frequency)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(rp2pio_statemachine_set_frequency_obj, rp2pio_statemachine_obj_set_frequency); + const mp_obj_property_t rp2pio_statemachine_frequency_obj = { .base.type = &mp_type_property, .proxy = {(mp_obj_t)&rp2pio_statemachine_get_frequency_obj, + (mp_obj_t)&rp2pio_statemachine_set_frequency_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +//| rxstall: bool +//| """True when the state machine has stalled due to a full RX FIFO since the last +//| `clear_rxfifo` call.""" +//| + +STATIC mp_obj_t rp2pio_statemachine_obj_get_rxstall(mp_obj_t self_in) { + rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_rp2pio_statemachine_get_rxstall(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(rp2pio_statemachine_get_rxstall_obj, rp2pio_statemachine_obj_get_rxstall); + +const mp_obj_property_t rp2pio_statemachine_rxstall_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&rp2pio_statemachine_get_rxstall_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +//| in_waiting: int +//| """The number of words available to readinto""" +//| + +STATIC mp_obj_t rp2pio_statemachine_obj_get_in_waiting(mp_obj_t self_in) { + rp2pio_statemachine_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_rp2pio_statemachine_get_in_waiting(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(rp2pio_statemachine_get_in_waiting_obj, rp2pio_statemachine_obj_get_in_waiting); + +const mp_obj_property_t rp2pio_statemachine_in_waiting_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&rp2pio_statemachine_get_in_waiting_obj, (mp_obj_t)&mp_const_none_obj, (mp_obj_t)&mp_const_none_obj}, }; @@ -425,20 +577,26 @@ STATIC const mp_rom_map_elem_t rp2pio_statemachine_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&rp2pio_statemachine_obj___exit___obj) }, -// { MP_ROM_QSTR(MP_QSTR_restart), MP_ROM_PTR(&rp2pio_statemachine_configure_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&rp2pio_statemachine_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_restart), MP_ROM_PTR(&rp2pio_statemachine_restart_obj) }, + { MP_ROM_QSTR(MP_QSTR_run), MP_ROM_PTR(&rp2pio_statemachine_run_obj) }, + { MP_ROM_QSTR(MP_QSTR_clear_rxfifo), MP_ROM_PTR(&rp2pio_statemachine_clear_rxfifo_obj) }, -// { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&rp2pio_statemachine_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&rp2pio_statemachine_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&rp2pio_statemachine_write_obj) }, -// { MP_ROM_QSTR(MP_QSTR_write_readinto), MP_ROM_PTR(&rp2pio_statemachine_write_readinto_obj) }, - { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&rp2pio_statemachine_frequency_obj) } + { MP_ROM_QSTR(MP_QSTR_write_readinto), MP_ROM_PTR(&rp2pio_statemachine_write_readinto_obj) }, + + { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&rp2pio_statemachine_frequency_obj) }, + { MP_ROM_QSTR(MP_QSTR_rxstall), MP_ROM_PTR(&rp2pio_statemachine_rxstall_obj) }, + { MP_ROM_QSTR(MP_QSTR_in_waiting), MP_ROM_PTR(&rp2pio_statemachine_in_waiting_obj) }, }; 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 5ff20a75bf6d0..0ebcca52913fa 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.h +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.h @@ -36,36 +36,44 @@ extern const mp_obj_type_t rp2pio_statemachine_type; // Construct an underlying SPI object. -extern void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, - const uint16_t* program, size_t program_len, +void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, + 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 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 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, + uint32_t wait_gpio_mask, bool exclusive_pin_use, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, + bool wait_for_txstall, bool auto_push, uint8_t push_threshold, bool in_shift_right); -extern void common_hal_rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self); -extern bool common_hal_rp2pio_statemachine_deinited(rp2pio_statemachine_obj_t *self); +void common_hal_rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self); +bool common_hal_rp2pio_statemachine_deinited(rp2pio_statemachine_obj_t *self); -// Writes out the given data. -extern bool common_hal_rp2pio_statemachine_write(rp2pio_statemachine_obj_t *self, const uint8_t *data, size_t len); +void common_hal_rp2pio_statemachine_never_reset(rp2pio_statemachine_obj_t *self); + +void common_hal_rp2pio_statemachine_restart(rp2pio_statemachine_obj_t *self); +void common_hal_rp2pio_statemachine_stop(rp2pio_statemachine_obj_t *self); +void common_hal_rp2pio_statemachine_run(rp2pio_statemachine_obj_t *self, const uint16_t *instructions, size_t len); -// // Reads in len bytes while outputting zeroes. -// extern bool common_hal_rp2pio_statemachine_read(rp2pio_statemachine_obj_t *self, uint8_t *data, size_t len, uint8_t write_value); +// Writes out the given data. +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); -// // Reads and write len bytes simultaneously. -// extern bool common_hal_rp2pio_statemachine_transfer(rp2pio_statemachine_obj_t *self, -// const uint8_t *data_out, size_t out_len, -// uint8_t *data_in, size_t in_len); +// 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); -// Return actual SPI bus frequency. -uint32_t common_hal_rp2pio_statemachine_get_frequency(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); -// This is used by the supervisor to claim SPI devices indefinitely. -// extern void common_hal_rp2pio_statemachine_never_reset(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); #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 dd5808cd5e4ef..68f7cf30191ea 100644 --- a/ports/raspberrypi/bindings/rp2pio/__init__.c +++ b/ports/raspberrypi/bindings/rp2pio/__init__.c @@ -28,18 +28,33 @@ #include "py/runtime.h" #include "bindings/rp2pio/StateMachine.h" +#include "bindings/rp2pio/__init__.h" //| """Hardware interface to RP2 series' programmable IO (PIO) peripheral.""" //| +//| def pins_are_sequential(pins: List[microcontroller.Pin]) -> bool: +//| """Return True if the pins have sequential GPIO numbers, False otherwise""" +//| ... +//| +STATIC mp_obj_t rp2pio_pins_are_sequential(const mp_obj_t pins) { + size_t len; + mp_obj_t *items; + mp_obj_get_array(pins, &len, &items); + return mp_obj_new_bool(common_hal_rp2pio_pins_are_sequential(len, items)); +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_1(rp2pio_pins_are_sequential_obj, rp2pio_pins_are_sequential); + STATIC const mp_rom_map_elem_t rp2pio_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_rp2pio) }, { MP_ROM_QSTR(MP_QSTR_StateMachine), MP_ROM_PTR(&rp2pio_statemachine_type) }, + { MP_ROM_QSTR(MP_QSTR_pins_are_sequential), MP_ROM_PTR(&rp2pio_pins_are_sequential_obj) }, }; 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/bindings/rp2pio/__init__.h b/ports/raspberrypi/bindings/rp2pio/__init__.h new file mode 100644 index 0000000000000..89dc7ff98fb28 --- /dev/null +++ b/ports/raspberrypi/bindings/rp2pio/__init__.h @@ -0,0 +1,29 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +bool common_hal_rp2pio_pins_are_sequential(size_t len, mp_obj_t *items); diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040/board.c b/ports/raspberrypi/boards/adafruit_feather_rp2040/board.c index 8686f6d0c2389..c4021a83e94e3 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040/board.c +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040/board.c @@ -30,10 +30,6 @@ #include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" void board_init(void) { - common_hal_never_reset_pin(&pin_GPIO17); - gpio_init(17); - gpio_set_dir(17, GPIO_OUT); - gpio_put(17, true); } bool board_requests_safe_mode(void) { diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.h index 6a2d063d79a4c..fba7dc3b19f8f 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.h +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.h @@ -10,5 +10,5 @@ #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO20) -// #define DEFAULT_UART_BUS_RX (&pin_PA11) -// #define DEFAULT_UART_BUS_TX (&pin_PA10) +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.mk index f4106b94a2c2e..84c4adabb7740 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.mk @@ -6,4 +6,4 @@ USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -INTERNAL_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "GD25Q64C" diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c b/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c index 1617ac865e9f4..8d5be961e0c58 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c @@ -14,23 +14,23 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO0) }, { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO6) }, { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, - { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO8) }, { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO13) }, { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO17) }, { 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_UART), MP_ROM_PTR(&board_uart_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/board.c b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/board.c new file mode 100644 index 0000000000000..e05589883d6d6 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/board.c @@ -0,0 +1,44 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +void board_init(void) { + common_hal_never_reset_pin(&pin_GPIO16); + gpio_init(16); + gpio_set_dir(16, GPIO_OUT); + gpio_put(16, true); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.h new file mode 100644 index 0000000000000..dad4e2eae8eeb --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.h @@ -0,0 +1,14 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit ItsyBitsy RP2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO17) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO20) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.mk new file mode 100644 index 0000000000000..965acff277507 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x239A +USB_PID = 0x80FE +USB_PRODUCT = "ItsyBitsy RP2040" +USB_MANUFACTURER = "Adafruit" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" diff --git a/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/pins.c b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/pins.c new file mode 100644 index 0000000000000..5c83bf3d74ad6 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/pins.c @@ -0,0 +1,43 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_GPIO25) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO14) }, + + { 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/raspberrypi/boards/adafruit_qtpy_rp2040/board.c b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/board.c new file mode 100644 index 0000000000000..332145ab8476a --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/board.c @@ -0,0 +1,44 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +void board_init(void) { + common_hal_never_reset_pin(&pin_GPIO11); + gpio_init(11); + gpio_set_dir(11, GPIO_OUT); + gpio_put(11, true); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.h new file mode 100644 index 0000000000000..a1947deaeb0cc --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.h @@ -0,0 +1,14 @@ +#define MICROPY_HW_BOARD_NAME "Adafruit QT Py RP2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO12) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO25) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO24) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO6) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO3) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO4) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO5) +#define DEFAULT_UART_BUS_TX (&pin_GPIO20) diff --git a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.mk new file mode 100644 index 0000000000000..8258f878336ea --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x239A +USB_PID = 0x80F8 +USB_PRODUCT = "QT Py RP2040" +USB_MANUFACTURER = "Adafruit" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" diff --git a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/pins.c b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/pins.c new file mode 100644 index 0000000000000..e9e726f35a1ed --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/pins.c @@ -0,0 +1,49 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO28) }, + + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO27) }, + + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO25) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_SDA1), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_SCL1), MP_ROM_PTR(&pin_GPIO23) }, + + { 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/raspberrypi/boards/pimoroni_keybow2040/board.c b/ports/raspberrypi/boards/pimoroni_keybow2040/board.c new file mode 100644 index 0000000000000..67486d4c230c1 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_keybow2040/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/pimoroni_keybow2040/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_keybow2040/mpconfigboard.h new file mode 100644 index 0000000000000..ecc127db681b1 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_keybow2040/mpconfigboard.h @@ -0,0 +1,39 @@ +#define MICROPY_HW_BOARD_NAME "Pimoroni Keybow 2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_SW0 (&pin_GPIO21) +#define MICROPY_HW_SW1 (&pin_GPIO20) +#define MICROPY_HW_SW2 (&pin_GPIO19) +#define MICROPY_HW_SW3 (&pin_GPIO18) +#define MICROPY_HW_SW4 (&pin_GPIO17) +#define MICROPY_HW_SW5 (&pin_GPIO16) +#define MICROPY_HW_SW6 (&pin_GPIO15) +#define MICROPY_HW_SW7 (&pin_GPIO14) +#define MICROPY_HW_SW8 (&pin_GPIO13) +#define MICROPY_HW_SW9 (&pin_GPIO12) +#define MICROPY_HW_SW10 (&pin_GPIO11) +#define MICROPY_HW_SW11 (&pin_GPIO10) +#define MICROPY_HW_SW12 (&pin_GPIO9) +#define MICROPY_HW_SW13 (&pin_GPIO8) +#define MICROPY_HW_SW14 (&pin_GPIO7) +#define MICROPY_HW_SW15 (&pin_GPIO6) + +#define MICROPY_HW_USER_SW (&pin_GPIO23) + +#define MICROPY_HW_I2C_INT (&pin_GPIO3) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) + +// These pins are unconnected +#define IGNORE_PIN_GPIO2 1 +#define IGNORE_PIN_GPIO22 1 +#define IGNORE_PIN_GPIO24 1 +#define IGNORE_PIN_GPIO25 1 +#define IGNORE_PIN_GPIO26 1 +#define IGNORE_PIN_GPIO27 1 +#define IGNORE_PIN_GPIO28 1 +#define IGNORE_PIN_GPIO29 1 diff --git a/ports/raspberrypi/boards/pimoroni_keybow2040/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_keybow2040/mpconfigboard.mk new file mode 100644 index 0000000000000..ad343c4e0d2e9 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_keybow2040/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x16D0 +USB_PID = 0x08C6 +USB_PRODUCT = "Keybow 2040" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/pimoroni_keybow2040/pins.c b/ports/raspberrypi/boards/pimoroni_keybow2040/pins.c new file mode 100644 index 0000000000000..c4cdb7b2933ae --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_keybow2040/pins.c @@ -0,0 +1,36 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_INT), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_SW0), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_SW1), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_SW2), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_SW3), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SW4), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SW5), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SW6), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SW7), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SW8), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_SW9), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_SW10), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_SW11), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_SW12), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_SW13), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SW14), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SW15), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_USER_SW), MP_ROM_PTR(&pin_GPIO23) }, + + { 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_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/board.c b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/board.c new file mode 100644 index 0000000000000..67486d4c230c1 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.h new file mode 100644 index 0000000000000..4261b9e0062fb --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.h @@ -0,0 +1,10 @@ +#define MICROPY_HW_BOARD_NAME "Pimoroni Pico LiPo (16MB)" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_VBUS_DETECT (&pin_GPIO24) +#define MICROPY_HW_BAT_SENSE (&pin_GPIO29) + +#define MICROPY_HW_USER_SW (&pin_GPIO23) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.mk new file mode 100644 index 0000000000000..129f408e5e9b9 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x2E8A +USB_PID = 0x1003 +USB_PRODUCT = "Pimoroni Pico LiPo (16MB)" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_16mb/pins.c b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/pins.c new file mode 100644 index 0000000000000..229d510eadd0e --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_16mb/pins.c @@ -0,0 +1,52 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_USER_SW), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_DETECT), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP26_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_BAT_SENSE), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/board.c b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/board.c new file mode 100644 index 0000000000000..67486d4c230c1 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.h new file mode 100644 index 0000000000000..e34a05abf27f5 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.h @@ -0,0 +1,10 @@ +#define MICROPY_HW_BOARD_NAME "Pimoroni Pico LiPo (4MB)" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_VBUS_DETECT (&pin_GPIO24) +#define MICROPY_HW_BAT_SENSE (&pin_GPIO29) + +#define MICROPY_HW_USER_SW (&pin_GPIO23) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.mk new file mode 100644 index 0000000000000..a82ee9c0ea0f5 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x2E8A +USB_PID = 0x1002 +USB_PRODUCT = "Pimoroni Pico LiPo (4MB)" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/pimoroni_picolipo_4mb/pins.c b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/pins.c new file mode 100644 index 0000000000000..229d510eadd0e --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picolipo_4mb/pins.c @@ -0,0 +1,52 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_USER_SW), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_DETECT), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP26_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_BAT_SENSE), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/boards/pimoroni_picosystem/board.c b/ports/raspberrypi/boards/pimoroni_picosystem/board.c new file mode 100644 index 0000000000000..67486d4c230c1 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picosystem/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.h new file mode 100644 index 0000000000000..8a61d6a76d630 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.h @@ -0,0 +1,47 @@ +#define MICROPY_HW_BOARD_NAME "Pimoroni PicoSystem" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_VBUS_DETECT (&pin_GPIO2) + +#define MICROPY_HW_LCD_RESET (&pin_GPIO4) +#define MICROPY_HW_LCD_CS (&pin_GPIO5) +#define MICROPY_HW_LCD_SCLK (&pin_GPIO6) +#define MICROPY_HW_LCD_MOSI (&pin_GPIO7) +#define MICROPY_HW_LCD_VSYNC (&pin_GPIO8) +#define MICROPY_HW_LCD_DS (&pin_GPIO9) + +#define MICROPY_HW_AUDIO (&pin_GPIO11) +#define MICROPY_HW_BACKLIGHT (&pin_GPIO12) +#define MICROPY_HW_VBUS_DETECT (&pin_GPIO2) + +#define MICROPY_HW_LED_G (&pin_GPIO13) +#define MICROPY_HW_LED_R (&pin_GPIO14) +#define MICROPY_HW_LED_B (&pin_GPIO15) + +#define MICROPY_HW_SW_Y (&pin_GPIO16) +#define MICROPY_HW_SW_X (&pin_GPIO17) +#define MICROPY_HW_SW_A (&pin_GPIO18) +#define MICROPY_HW_SW_B (&pin_GPIO19) + +#define MICROPY_HW_SW_DOWN (&pin_GPIO20) +#define MICROPY_HW_SW_RIGHT (&pin_GPIO21) +#define MICROPY_HW_SW_LEFT (&pin_GPIO22) +#define MICROPY_HW_SW_UP (&pin_GPIO23) + +#define MICROPY_HW_CHARGE_STAT (&pin_GPIO24) + +#define MICROPY_HW_BAT_SENSE (&pin_GPIO26) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO6) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO7) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) + +// These pins are unconnected +#define IGNORE_PIN_GPIO3 1 +#define IGNORE_PIN_GPIO10 1 +#define IGNORE_PIN_GPIO25 1 +#define IGNORE_PIN_GPIO27 1 +#define IGNORE_PIN_GPIO28 1 +#define IGNORE_PIN_GPIO29 1 diff --git a/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.mk new file mode 100644 index 0000000000000..f00fb64cc9544 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x16D0 +USB_PID = 0x08C8 +USB_PRODUCT = "PicoSystem" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/pimoroni_picosystem/pins.c b/ports/raspberrypi/boards/pimoroni_picosystem/pins.c new file mode 100644 index 0000000000000..30aafacbad43e --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_picosystem/pins.c @@ -0,0 +1,43 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_VBUS_DETECT), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_LCD_RESET), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SCLK), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_LCD_VSYNC), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_AUDIO), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_BACKLIGHT), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_SW_Y), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SW_X), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SW_A), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SW_B), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_SW_DOWN), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_SW_RIGHT), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_SW_LEFT), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_SW_UP), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_CHARGE_STAT), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_BAT_SENSE), MP_ROM_PTR(&pin_GPIO26) }, + + { 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/raspberrypi/boards/pimoroni_tiny2040/board.c b/ports/raspberrypi/boards/pimoroni_tiny2040/board.c new file mode 100644 index 0000000000000..67486d4c230c1 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_tiny2040/board.c @@ -0,0 +1,37 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.h new file mode 100644 index 0000000000000..8f188959cb7d8 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.h @@ -0,0 +1,24 @@ +#define MICROPY_HW_BOARD_NAME "Pimoroni Tiny 2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_LED_R (&pin_GPIO18) +#define MICROPY_HW_LED_G (&pin_GPIO19) +#define MICROPY_HW_LED_B (&pin_GPIO20) + +#define MICROPY_HW_USER_SW (&pin_GPIO23) + +// These pins are unconnected +#define IGNORE_PIN_GPIO8 1 +#define IGNORE_PIN_GPIO9 1 +#define IGNORE_PIN_GPIO10 1 +#define IGNORE_PIN_GPIO11 1 +#define IGNORE_PIN_GPIO12 1 +#define IGNORE_PIN_GPIO13 1 +#define IGNORE_PIN_GPIO14 1 +#define IGNORE_PIN_GPIO15 1 +#define IGNORE_PIN_GPIO16 1 +#define IGNORE_PIN_GPIO17 1 +#define IGNORE_PIN_GPIO21 1 +#define IGNORE_PIN_GPIO22 1 +#define IGNORE_PIN_GPIO24 1 +#define IGNORE_PIN_GPIO25 1 diff --git a/ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.mk new file mode 100644 index 0000000000000..74877822372df --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x16D0 +USB_PID = 0x08C7 +USB_PRODUCT = "Tiny 2040" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/pimoroni_tiny2040/pins.c b/ports/raspberrypi/boards/pimoroni_tiny2040/pins.c new file mode 100644 index 0000000000000..de79ee7320bfc --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_tiny2040/pins.c @@ -0,0 +1,39 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_USER_SW), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP26_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP27_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP28_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_GP29_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + + { 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/raspberrypi/boards/raspberry_pi_pico/board.c b/ports/raspberrypi/boards/raspberry_pi_pico/board.c index 80ec5de32b095..67486d4c230c1 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/boards/raspberry_pi_pico/mpconfigboard.h b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h index 4b0a220287a59..efb2fc34029ab 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h +++ b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h @@ -1,15 +1,2 @@ -// LEDs -// #define MICROPY_HW_LED_STATUS (&pin_PA17) - #define MICROPY_HW_BOARD_NAME "Raspberry Pi Pico" #define MICROPY_HW_MCU_NAME "rp2040" - -// #define DEFAULT_I2C_BUS_SCL (&pin_PA23) -// #define DEFAULT_I2C_BUS_SDA (&pin_PA22) - -// #define DEFAULT_SPI_BUS_SCK (&pin_PB11) -// #define DEFAULT_SPI_BUS_MOSI (&pin_PB10) -// #define DEFAULT_SPI_BUS_MISO (&pin_PA12) - -// #define DEFAULT_UART_BUS_RX (&pin_PA11) -// #define DEFAULT_UART_BUS_TX (&pin_PA10) diff --git a/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk index 54c1306606480..608ca280df588 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk +++ b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk @@ -6,6 +6,6 @@ USB_MANUFACTURER = "Raspberry Pi" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -INTERNAL_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/raspberry_pi_pico/pins.c b/ports/raspberrypi/boards/raspberry_pi_pico/pins.c index 913676ad265f6..057eaec2aff00 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/pins.c +++ b/ports/raspberrypi/boards/raspberry_pi_pico/pins.c @@ -24,16 +24,29 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_SMPS_MODE), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP26_A0), MP_ROM_PTR(&pin_GPIO26) }, { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27_A1), MP_ROM_PTR(&pin_GPIO27) }, { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28_A2), MP_ROM_PTR(&pin_GPIO28) }, { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/board.c b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/board.c new file mode 100644 index 0000000000000..c4021a83e94e3 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.h new file mode 100644 index 0000000000000..d7dd7a6376cf7 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.h @@ -0,0 +1,12 @@ +#define MICROPY_HW_BOARD_NAME "SparkFun MicroMod ATP - RP2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO14) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO15) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO12) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.mk new file mode 100644 index 0000000000000..2ed559d8dbc92 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x1B4F +USB_PID = 0x0024 +USB_PRODUCT = "MicroMod RP2040" +USB_MANUFACTURER = "SparkFun" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxM" diff --git a/ports/raspberrypi/boards/sparkfun_micromod_rp2040/pins.c b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/pins.c new file mode 100644 index 0000000000000..5414dd3e2bbbe --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_micromod_rp2040/pins.c @@ -0,0 +1,105 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + // D (Digital only) pins (D0,D1) + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO6) }, // GPIO6 - D0 + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO7) }, // GPIO7 - D1 + + // A (ADC) pins (A0,A1) + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, // GPIO26 - A0 | ADC0 + { MP_ROM_QSTR(MP_QSTR_ADC0), MP_ROM_PTR(&pin_GPIO26) }, // ADC0 alias + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, // GPIO27 - A1 | ADC1 + { MP_ROM_QSTR(MP_QSTR_ADC1), MP_ROM_PTR(&pin_GPIO27) }, // ADC1 alias + + // G (General/BUS) pins (G0-G7, G8 NC, G9-G10, G11 NC) + { MP_ROM_QSTR(MP_QSTR_G0), MP_ROM_PTR(&pin_GPIO16) }, // GPIO16 - G0 | BUS0 + { MP_ROM_QSTR(MP_QSTR_BUS0), MP_ROM_PTR(&pin_GPIO16) }, // BUS0 alias + { MP_ROM_QSTR(MP_QSTR_G1), MP_ROM_PTR(&pin_GPIO17) }, // GPIO17 - G1 | BUS1 + { MP_ROM_QSTR(MP_QSTR_BUS1), MP_ROM_PTR(&pin_GPIO17) }, // BUS1 alias + { MP_ROM_QSTR(MP_QSTR_G2), MP_ROM_PTR(&pin_GPIO18) }, // GPIO18 - G2 | BUS2 + { MP_ROM_QSTR(MP_QSTR_BUS2), MP_ROM_PTR(&pin_GPIO18) }, // BUS2 alias + { MP_ROM_QSTR(MP_QSTR_G3), MP_ROM_PTR(&pin_GPIO19) }, // GPIO19 - G3 | BUS3 + { MP_ROM_QSTR(MP_QSTR_BUS3), MP_ROM_PTR(&pin_GPIO19) }, // BUS3 alias + { MP_ROM_QSTR(MP_QSTR_G4), MP_ROM_PTR(&pin_GPIO20) }, // GPIO20 - G4 | BUS4 | SPI_CIPO + { MP_ROM_QSTR(MP_QSTR_BUS4), MP_ROM_PTR(&pin_GPIO20) }, // BUS4 alias + { MP_ROM_QSTR(MP_QSTR_G5), MP_ROM_PTR(&pin_GPIO21) }, // GPIO21 - G5 | BUS5 | SPI_CS + { MP_ROM_QSTR(MP_QSTR_BUS5), MP_ROM_PTR(&pin_GPIO21) }, // BUS5 alias + { MP_ROM_QSTR(MP_QSTR_G6), MP_ROM_PTR(&pin_GPIO22) }, // GPIO22 - G6 | BUS6 | SPI_SCK + { MP_ROM_QSTR(MP_QSTR_BUS6), MP_ROM_PTR(&pin_GPIO22) }, // BUS6 alias + { MP_ROM_QSTR(MP_QSTR_G7), MP_ROM_PTR(&pin_GPIO23) }, // GPIO23 - G7 | BUS7 | SPI_COPI + { MP_ROM_QSTR(MP_QSTR_BUS7), MP_ROM_PTR(&pin_GPIO23) }, // BUS7 alias + // NC - G8 + { MP_ROM_QSTR(MP_QSTR_G9), MP_ROM_PTR(&pin_GPIO28) }, // GPIO28- G9 | BUS9 | ADC_D- | CAM_HSYNC + { MP_ROM_QSTR(MP_QSTR_BUS9), MP_ROM_PTR(&pin_GPIO28) }, // BUS9 alias + { MP_ROM_QSTR(MP_QSTR_ADC_DM), MP_ROM_PTR(&pin_GPIO28) }, // ADC_DM alias + { MP_ROM_QSTR(MP_QSTR_CAM_HSYNC), MP_ROM_PTR(&pin_GPIO28) }, // CAM_HSYNC alias + { MP_ROM_QSTR(MP_QSTR_G10), MP_ROM_PTR(&pin_GPIO25) }, // GPIO25 - G10 | BUS10 | ADC_D+ | CAM_VSYNC + { MP_ROM_QSTR(MP_QSTR_BUS10), MP_ROM_PTR(&pin_GPIO25) }, // BUS10 alias + { MP_ROM_QSTR(MP_QSTR_ADC_DP), MP_ROM_PTR(&pin_GPIO25) }, // ADC_DP alias + { MP_ROM_QSTR(MP_QSTR_CAM_VSYNC), MP_ROM_PTR(&pin_GPIO25) }, // CAM_VSYNC alias + // NC - G11 + + // PWM pins (PWM0,PWM1) + { MP_ROM_QSTR(MP_QSTR_PWM0), MP_ROM_PTR(&pin_GPIO13) }, // GPIO13 - PWM0 + { MP_ROM_QSTR(MP_QSTR_PWM1), MP_ROM_PTR(&pin_GPIO24) }, // GPIO24 - PWM1 | AUD_MCLK + + // AUD (audio) + { MP_ROM_QSTR(MP_QSTR_AUD_MCLK), MP_ROM_PTR(&pin_GPIO24) }, // GPIO24 - AUD_MCLK | PWM1 + { MP_ROM_QSTR(MP_QSTR_AUD_OUT), MP_ROM_PTR(&pin_GPIO10) }, // GPIO10 - AUD_OUT | SDIO_DAT2 + { MP_ROM_QSTR(MP_QSTR_AUD_IN), MP_ROM_PTR(&pin_GPIO11) }, // GPIO11 - AUD_IN | SDIO_DAT1 + { MP_ROM_QSTR(MP_QSTR_AUD_LRCLK), MP_ROM_PTR(&pin_GPIO2) }, // GPIO2 - AUD_LRCLK | CTS1 + { MP_ROM_QSTR(MP_QSTR_AUD_BCLK), MP_ROM_PTR(&pin_GPIO3) }, // GPIO3 - AUD_BCLK | UART_RTS1 + + // Battery Voltage Monitor + { MP_ROM_QSTR(MP_QSTR_BATT_VIN3), MP_ROM_PTR(&pin_GPIO29) }, // GPIO29 - BATT_VIN/3 (ADC03) + + + // I2C + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, // GPIO4 - SDA + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, // GPIO5 - SCL + + { MP_ROM_QSTR(MP_QSTR_I2C_INT), MP_ROM_PTR(&pin_GPIO8) }, // GPIO9 - I2C_INT | TX2 + + // SPI + { MP_ROM_QSTR(MP_QSTR_CIPO), MP_ROM_PTR(&pin_GPIO20) }, // GPIO20 - CIPO | SPI_CIPO | G4 + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO20) }, // MISO alias + { MP_ROM_QSTR(MP_QSTR_COPI), MP_ROM_PTR(&pin_GPIO23) }, // GPIO23 - COPI | SPI_COPI | G7 + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, // MOSI alias + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO22) }, // GPIO22 - SCK | SPI_SCK | G6 + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_GPIO21) }, // GPIO21 - /CS | SPI_/CS | G5 + + // SDI/SPI1 + { MP_ROM_QSTR(MP_QSTR_SDIO_CLK), MP_ROM_PTR(&pin_GPIO14) }, // GPIO14 - SDIO SCK | SDIO_CLK + { MP_ROM_QSTR(MP_QSTR_SPI_SCK1), MP_ROM_PTR(&pin_GPIO14) }, // SPI_SCK1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_CMD), MP_ROM_PTR(&pin_GPIO15) }, // GPIO15 - SDIO CMD | SDIO_CMD + { MP_ROM_QSTR(MP_QSTR_SPI_COPI1), MP_ROM_PTR(&pin_GPIO15) },// SPI_COPI1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA0), MP_ROM_PTR(&pin_GPIO12) },// GPIO12 - SDIO DATA0 | SDIO_DATA0 + { MP_ROM_QSTR(MP_QSTR_SPI_CIPO1), MP_ROM_PTR(&pin_GPIO12) }, // SPI_CIPO1 alias + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA1), MP_ROM_PTR(&pin_GPIO11) },// GPIO11 - SDIO DATA1 | SDIO_DATA1 | AUD_IN + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA2), MP_ROM_PTR(&pin_GPIO10) },// GPIO10 - SDIO DATA2 | SDIO_DATA2 | AUD_OUT + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA3), MP_ROM_PTR(&pin_GPIO9) },// GPIO9 - SDIO DATA3 | SDIO_DATA3 | SPI_CS1 + { MP_ROM_QSTR(MP_QSTR_SPI_CS1), MP_ROM_PTR(&pin_GPIO9) }, // SPI_CS1 alias + + // Status LED + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_GPIO25) }, // GPIO25 - LED_BUILTIN | STAT | Blue LED | G10 + + // UART + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, // GPIO1 - UART RX | UART_RX1 | RX1 + { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_GPIO1) }, // RX1 alias + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, // GPIO0 - UART TX | UART_TX1 | TX1 + { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_GPIO0) }, // TX1 alias + { MP_ROM_QSTR(MP_QSTR_CTS), MP_ROM_PTR(&pin_GPIO2) }, // GPIO2 - UART CTS | CTS1 (TRACEDATA3) + { MP_ROM_QSTR(MP_QSTR_CTS1), MP_ROM_PTR(&pin_GPIO2) }, // CTS1 alias + { MP_ROM_QSTR(MP_QSTR_RTS), MP_ROM_PTR(&pin_GPIO3) }, // GPIO3 - UART RTS | RTS1 + { MP_ROM_QSTR(MP_QSTR_RTS1), MP_ROM_PTR(&pin_GPIO3) }, // RTS1 alias + + { MP_ROM_QSTR(MP_QSTR_RX2), MP_ROM_PTR(&pin_GPIO9) }, // GPIO9 - UART RX | UART_RX2 | RX2 | SDIO_DAT3 | SPI_CS1 + { MP_ROM_QSTR(MP_QSTR_TX2), MP_ROM_PTR(&pin_GPIO8) }, // GPIO8 - UART TX | UART_TX2 | TX2 | I2C_INT + + // Board objects + { 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/raspberrypi/boards/sparkfun_pro_micro_rp2040/board.c b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/board.c new file mode 100644 index 0000000000000..c4021a83e94e3 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/mpconfigboard.h new file mode 100644 index 0000000000000..eb807097b5223 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/mpconfigboard.h @@ -0,0 +1,14 @@ +#define MICROPY_HW_BOARD_NAME "SparkFun Pro Micro RP2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO25) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO17) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO16) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO22) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO23) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO20) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/mpconfigboard.mk new file mode 100644 index 0000000000000..d02d14267f429 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x1B4F +USB_PID = 0x0026 +USB_PRODUCT = "Pro Micro RP2040" +USB_MANUFACTURER = "SparkFun" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxM" diff --git a/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/pins.c b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/pins.c new file mode 100644 index 0000000000000..b372fcb862cdf --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2040/pins.c @@ -0,0 +1,44 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_D26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_D28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_D29), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO25) }, + + { 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/raspberrypi/boards/sparkfun_thing_plus_rp2040/board.c b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/board.c new file mode 100644 index 0000000000000..c4021a83e94e3 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/board.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "supervisor/board.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +void board_init(void) { +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/mpconfigboard.h new file mode 100644 index 0000000000000..6c307ec890a4e --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/mpconfigboard.h @@ -0,0 +1,14 @@ +#define MICROPY_HW_BOARD_NAME "SparkFun Thing Plus - RP2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO8) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO7) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO6) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO14) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO15) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO12) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/mpconfigboard.mk new file mode 100644 index 0000000000000..101adbfa4bac0 --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x1B4F +USB_PID = 0x0025 +USB_PRODUCT = "Thing Plus RP2040" +USB_MANUFACTURER = "SparkFun" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxM" diff --git a/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/pins.c b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/pins.c new file mode 100644 index 0000000000000..8f63a9bdf264b --- /dev/null +++ b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/pins.c @@ -0,0 +1,37 @@ +#include "shared-bindings/board/__init__.h" + +STATIC const mp_rom_map_elem_t board_global_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO9)}, + + { 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/raspberrypi/boot_stage2.ld b/ports/raspberrypi/boot_stage2.ld new file mode 100644 index 0000000000000..c29429062c1c6 --- /dev/null +++ b/ports/raspberrypi/boot_stage2.ld @@ -0,0 +1,13 @@ +MEMORY { + /* We are loaded to the top 256 bytes of SRAM, which is above the bootrom + stack. Note 4 bytes occupied by checksum. */ + SRAM(rx) : ORIGIN = 0x20041f00, LENGTH = 252 +} + +SECTIONS { + . = ORIGIN(SRAM); + .text : { + *(.entry.*) + *(.text.*) + } >SRAM +} diff --git a/ports/raspberrypi/bs2_default_padded_checksummed.S b/ports/raspberrypi/bs2_default_padded_checksummed.S deleted file mode 100644 index d77f4867c6479..0000000000000 --- a/ports/raspberrypi/bs2_default_padded_checksummed.S +++ /dev/null @@ -1,20 +0,0 @@ -// Padded and checksummed version of: /Users/graham/dev/mu/pico_sdk/cmake-build-debug-mu/src/rp2_common/boot_stage2/bs2_default.bin - -.section .boot2, "a" - -.byte 0x00, 0xb5, 0x2f, 0x4b, 0x21, 0x20, 0x58, 0x60, 0x98, 0x68, 0x02, 0x21, 0x88, 0x43, 0x98, 0x60 -.byte 0xd8, 0x60, 0x18, 0x61, 0x58, 0x61, 0x2b, 0x4b, 0x00, 0x21, 0x99, 0x60, 0x02, 0x21, 0x59, 0x61 -.byte 0x01, 0x21, 0xf0, 0x22, 0x99, 0x50, 0x28, 0x49, 0x19, 0x60, 0x01, 0x21, 0x99, 0x60, 0x35, 0x20 -.byte 0x00, 0xf0, 0x3e, 0xf8, 0x02, 0x22, 0x90, 0x42, 0x14, 0xd0, 0x06, 0x21, 0x19, 0x66, 0x00, 0xf0 -.byte 0x2e, 0xf8, 0x19, 0x6e, 0x01, 0x21, 0x19, 0x66, 0x00, 0x20, 0x18, 0x66, 0x1a, 0x66, 0x00, 0xf0 -.byte 0x26, 0xf8, 0x19, 0x6e, 0x19, 0x6e, 0x19, 0x6e, 0x05, 0x20, 0x00, 0xf0, 0x29, 0xf8, 0x01, 0x21 -.byte 0x08, 0x42, 0xf9, 0xd1, 0x00, 0x21, 0x99, 0x60, 0x18, 0x49, 0x19, 0x60, 0x00, 0x21, 0x59, 0x60 -.byte 0x17, 0x49, 0x18, 0x48, 0x01, 0x60, 0x01, 0x21, 0x99, 0x60, 0xeb, 0x21, 0x19, 0x66, 0xa0, 0x21 -.byte 0x19, 0x66, 0x00, 0xf0, 0x0c, 0xf8, 0x00, 0x21, 0x99, 0x60, 0x13, 0x49, 0x11, 0x48, 0x01, 0x60 -.byte 0x01, 0x21, 0x99, 0x60, 0x01, 0xbc, 0x00, 0x28, 0x00, 0xd1, 0x10, 0x48, 0x00, 0x47, 0x03, 0xb5 -.byte 0x99, 0x6a, 0x04, 0x20, 0x01, 0x42, 0xfb, 0xd0, 0x01, 0x20, 0x01, 0x42, 0xf8, 0xd1, 0x03, 0xbd -.byte 0x02, 0xb5, 0x18, 0x66, 0x18, 0x66, 0xff, 0xf7, 0xf2, 0xff, 0x18, 0x6e, 0x18, 0x6e, 0x02, 0xbd -.byte 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x07, 0x00, 0x00, 0x03, 0x5f, 0x00 -.byte 0x21, 0x22, 0x00, 0x00, 0xf4, 0x00, 0x00, 0x18, 0x22, 0x20, 0x00, 0xa0, 0x01, 0x01, 0x00, 0x10 -.byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -.byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x27, 0x2a, 0x60 diff --git a/ports/raspberrypi/common-hal/analogio/AnalogIn.c b/ports/raspberrypi/common-hal/analogio/AnalogIn.c index c51a749295d1b..7db2956b03c36 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 ee9976e348d5d..c322a6776f362 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 adafa15d5c913..7afa773d3091d 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 new file mode 100644 index 0000000000000..0ad44c2527f27 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/I2SOut.c @@ -0,0 +1,227 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include + +#include "mpconfigport.h" + +#include "py/gc.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "common-hal/audiobusio/I2SOut.h" +#include "shared-bindings/audiobusio/I2SOut.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/audiocore/__init__.h" +#include "bindings/rp2pio/StateMachine.h" +#include "supervisor/shared/translate.h" + +const uint16_t i2s_program[] = { +// ; Load the next set of samples +// ; /--- LRCLK +// ; |/-- BCLK +// ; || +// pull noblock side 0b01 ; Loads OSR with the next FIFO value or X + 0x8880, +// mov x osr side 0b01 ; Save the new value in case we need it again + 0xa827, +// set y 14 side 0b01 + 0xe84e, +// bitloop1: +// out pins 1 side 0b00 [2] + 0x6201, +// jmp y-- bitloop1 side 0b01 [2] + 0x0a83, +// out pins 1 side 0b10 [2] + 0x7201, +// set y 14 side 0b11 [2] + 0xfa4e, +// bitloop0: +// out pins 1 side 0b10 [2] + 0x7201, +// jmp y-- bitloop0 side 0b11 [2] + 0x1a87, +// out pins 1 side 0b00 [2] + 0x6201 +}; + +const uint16_t i2s_program_left_justified[] = { +// ; Load the next set of samples +// ; /--- LRCLK +// ; |/-- BCLK +// ; || +// pull noblock side 0b11 ; Loads OSR with the next FIFO value or X + 0x9880, +// mov x osr side 0b11 ; Save the new value in case we need it again + 0xb827, +// set y 14 side 0b11 + 0xf84e, +// bitloop1: +// out pins 1 side 0b00 [2] + 0x6201, +// jmp y-- bitloop1 side 0b01 [2] + 0x0a83, +// out pins 1 side 0b10 [2] + 0x6201, +// set y 14 side 0b01 [2] + 0xea4e, +// bitloop0: +// out pins 1 side 0b10 [2] + 0x7201, +// jmp y-- bitloop0 side 0b11 [2] + 0x1a87, +// out pins 1 side 0b10 [2] + 0x7201 +}; + +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) { + 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; + 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]); + ; + } + + // Use the state machine to manage pins. + common_hal_rp2pio_statemachine_construct(&self->state_machine, + program, program_len, + 44100 * 32 * 6, // Clock at 44.1 khz to warm the DAC up. + NULL, 0, + data, 1, 0, 0xffffffff, // out pin + NULL, 0, // in pins + 0, 0, // in pulls + NULL, 0, 0, 0x1f, // set pins + bit_clock, 2, 0, 0x1f, // sideset pins + 0, // wait gpio pins + true, // exclusive pin use + false, 32, false, // shift out left to start with MSB + false, // Wait for txstall + false, 32, false); // in settings + + self->playing = false; + audio_dma_init(&self->dma); +} + +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) { + if (common_hal_audiobusio_i2sout_deinited(self)) { + return; + } + + 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) { + if (common_hal_audiobusio_i2sout_get_playing(self)) { + common_hal_audiobusio_i2sout_stop(self); + } + uint8_t bits_per_sample = audiosample_bits_per_sample(sample); + // Make sure we transmit a minimum of 16 bits. + // TODO: Maybe we need an intermediate object to upsample instead. This is + // only needed for some I2S devices that expect at least 8. + if (bits_per_sample < 16) { + bits_per_sample = 16; + } + // We always output stereo so output twice as many bits. + uint16_t bits_per_sample_output = bits_per_sample * 2; + size_t clocks_per_bit = 6; + uint32_t frequency = bits_per_sample_output * audiosample_sample_rate(sample); + common_hal_rp2pio_statemachine_set_frequency(&self->state_machine, clocks_per_bit * frequency); + common_hal_rp2pio_statemachine_restart(&self->state_machine); + + uint8_t channel_count = audiosample_channel_count(sample); + if (channel_count > 2) { + mp_raise_ValueError(translate("Too many channels in sample.")); + } + + audio_dma_result result = audio_dma_setup_playback( + &self->dma, + sample, + loop, + false, // single channel + 0, // audio channel + true, // output signed + bits_per_sample, + (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) { + common_hal_audiobusio_i2sout_stop(self); + mp_raise_RuntimeError(translate("No DMA channel found")); + } else if (result == AUDIO_DMA_MEMORY_ERROR) { + common_hal_audiobusio_i2sout_stop(self); + mp_raise_RuntimeError(translate("Unable to allocate buffers for signed conversion")); + } + + // Turn on the state machine's clock. + + self->playing = true; +} + +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) { + // Maybe: Clear any overrun/underrun errors + + audio_dma_resume(&self->dma); +} + +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) { + audio_dma_stop(&self->dma); + + common_hal_rp2pio_statemachine_stop(&self->state_machine); + + self->playing = false; +} + +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); + } + return playing; +} diff --git a/ports/raspberrypi/common-hal/audiobusio/I2SOut.h b/ports/raspberrypi/common-hal/audiobusio/I2SOut.h new file mode 100644 index 0000000000000..851e86c8a9ab1 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/I2SOut.h @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOBUSIO_I2SOUT_H +#define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOBUSIO_I2SOUT_H + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/rp2pio/StateMachine.h" + +#include "audio_dma.h" +#include "py/obj.h" + +// We don't bit pack because we'll only have two at most. Its better to save code size instead. +typedef struct { + mp_obj_base_t base; + bool left_justified; + rp2pio_statemachine_obj_t state_machine; + bool playing; + audio_dma_t dma; +} audiobusio_i2sout_obj_t; + +void i2sout_reset(void); + +#endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOBUSIO_I2SOUT_H diff --git a/ports/raspberrypi/common-hal/audiobusio/PDMIn.c b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c new file mode 100644 index 0000000000000..3f2b448eacae1 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c @@ -0,0 +1,175 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/mperrno.h" +#include "py/runtime.h" +#include "shared-bindings/audiobusio/PDMIn.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "supervisor/shared/translate.h" + +#include "audio_dma.h" + +#define OVERSAMPLING 64 +#define SAMPLES_PER_BUFFER 32 + +// MEMS microphones must be clocked at at least 1MHz. +#define MIN_MIC_CLOCK 1000000 + +const uint16_t pdmin[] = { + // in pins 1 side 0b1 + 0x5001, + // push iffull side 0b0 + 0x8040 +}; + +// 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) { + 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.")); + } + + // Use the state machine to manage pins. + common_hal_rp2pio_statemachine_construct(&self->state_machine, + pdmin, sizeof(pdmin) / sizeof(pdmin[0]), + 44100 * 32 * 2, // Clock at 44.1 khz to warm the DAC up. + NULL, 0, + NULL, 1, 0, 0xffffffff, // out pin + data_pin, 1, // in pins + 0, 0, // in pulls + NULL, 0, 0, 0x1f, // set pins + clock_pin, 1, 0, 0x1f, // sideset pins + 0, // wait gpio pins + true, // exclusive pin use + false, 32, false, // out settings + false, // Wait for txstall + false, 32, true); // in settings + + uint32_t actual_frequency = common_hal_rp2pio_statemachine_get_frequency(&self->state_machine); + if (actual_frequency < MIN_MIC_CLOCK) { + mp_raise_ValueError(translate("sampling rate out of range")); + } + + self->sample_rate = actual_frequency / oversample; + self->bit_depth = bit_depth; +} + +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) { + 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) { + return self->bit_depth; +} + +uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t *self) { + return self->sample_rate; +} + +// a windowed sinc filter for 44 khz, 64 samples +// +// This filter is good enough to use for lower sample rates as +// well. It does not increase the noise enough to be a problem. +// +// In the long run we could use a fast filter like this to do the +// decimation and initial filtering in real time, filtering to a +// 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] = { + 0, 2, 9, 21, 39, 63, 94, 132, + 179, 236, 302, 379, 467, 565, 674, 792, + 920, 1055, 1196, 1341, 1487, 1633, 1776, 1913, + 2042, 2159, 2263, 2352, 2422, 2474, 2506, 2516, + 2506, 2474, 2422, 2352, 2263, 2159, 2042, 1913, + 1776, 1633, 1487, 1341, 1196, 1055, 920, 792, + 674, 565, 467, 379, 302, 236, 179, 132, + 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) + +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; + } + ); + } + return running_sum; +} + +// 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 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)); + 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)); + // 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; + } else { + output_buffer[output_count] = value; + } + output_count++; + } + + return output_count; +} + +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/audiobusio/PDMIn.h b/ports/raspberrypi/common-hal/audiobusio/PDMIn.h new file mode 100644 index 0000000000000..995ffb5d78a0c --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/PDMIn.h @@ -0,0 +1,50 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOBUSIO_AUDIOOUT_H +#define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOBUSIO_AUDIOOUT_H + +#include "common-hal/microcontroller/Pin.h" +#include "bindings/rp2pio/StateMachine.h" + +#include "extmod/vfs_fat.h" +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint32_t sample_rate; + uint8_t serializer; + uint8_t clock_unit; + uint8_t bytes_per_sample; + uint8_t bit_depth; + rp2pio_statemachine_obj_t state_machine; +} audiobusio_pdmin_obj_t; + +void pdmin_reset(void); + +void pdmin_background(void); + +#endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOBUSIO_AUDIOOUT_H diff --git a/ports/raspberrypi/common-hal/audiobusio/__init__.c b/ports/raspberrypi/common-hal/audiobusio/__init__.c new file mode 100644 index 0000000000000..87db404966ab1 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/__init__.c @@ -0,0 +1 @@ +// No audiobusio module functions. diff --git a/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c new file mode 100644 index 0000000000000..4fef53ff0a163 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c @@ -0,0 +1,235 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "common-hal/audiopwmio/PWMAudioOut.h" + +#include +#include + +#include "extmod/vfs_fat.h" +#include "py/gc.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "shared-bindings/pwmio/PWMOut.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/microcontroller/Processor.h" +#include "supervisor/shared/tick.h" +#include "supervisor/shared/translate.h" + +#include "src/rp2040/hardware_structs/include/hardware/structs/dma.h" +#include "src/rp2_common/hardware_pwm/include/hardware/pwm.h" + +#define NUM_DMA_TIMERS 4 + +void audiopwmout_reset() { + for (size_t i = 0; i < NUM_DMA_TIMERS; i++) { + dma_hw->timer[i] = 0; + } +} + +// 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) { + 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")); + } + if (pwm_gpio_to_channel(left_channel->number) != 0) { + mp_raise_ValueError(translate("Stereo left must be on PWM channel A")); + } + if (pwm_gpio_to_channel(right_channel->number) != 1) { + mp_raise_ValueError(translate("Stereo right must be on PWM channel B")); + } + } + + // Typically pwmout doesn't let us change frequency with two objects on the + // same PWM slice. However, we have private access to it so we can do what + // we want. ;-) We mark ourselves variable only if we're a mono output to + // prevent other PWM use on the other channel. If stereo, we say fixed + // frequency so we can allocate with ourselves. + bool mono = right_channel == NULL; + + // We don't actually know our frequency yet so just pick one that shouldn't + // match anyone else. (We'll only know the frequency once we play something + // back.) + uint32_t frequency = 12500; + + // Make sure the PWMOut's are "deinited" by default. + self->left_pwm.pin = NULL; + self->right_pwm.pin = NULL; + + pwmout_result_t result = common_hal_pwmio_pwmout_construct(&self->left_pwm, + left_channel, 0, frequency, mono); + if (result == PWMOUT_OK && right_channel != NULL) { + result = common_hal_pwmio_pwmout_construct(&self->right_pwm, + right_channel, 0, frequency, false); + if (result != PWMOUT_OK) { + common_hal_pwmio_pwmout_deinit(&self->left_pwm); + } + } + if (result != PWMOUT_OK) { + mp_raise_RuntimeError(translate("All timers in use")); + } + + claim_pin(left_channel); + if (right_channel != NULL) { + claim_pin(right_channel); + } + + audio_dma_init(&self->dma); + + self->quiescent_value = quiescent_value; +} + +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) { + if (common_hal_audiopwmio_pwmaudioout_deinited(self)) { + return; + } + if (common_hal_audiopwmio_pwmaudioout_get_playing(self)) { + common_hal_audiopwmio_pwmaudioout_stop(self); + } + + // TODO: ramp the pwm down from quiescent value to 0 + common_hal_pwmio_pwmout_deinit(&self->left_pwm); + common_hal_pwmio_pwmout_deinit(&self->right_pwm); + + audio_dma_deinit(&self->dma); +} + +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); + } + + // TODO: Share pacing timers based on frequency. + size_t pacing_timer = NUM_DMA_TIMERS; + for (size_t i = 0; i < NUM_DMA_TIMERS; i++) { + if (dma_hw->timer[i] == 0) { + pacing_timer = i; + } + break; + } + 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; + 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); + } + + pwmio_pwmout_set_top(&self->left_pwm, 1023); + + audio_dma_result result = audio_dma_setup_playback( + &self->dma, + sample, + loop, + false, // single channel + 0, // audio channel + false, // output signed + 10, + (uint32_t)tx_register, // output register + 0x3b + pacing_timer); // data request line + + if (result == AUDIO_DMA_DMA_BUSY) { + // common_hal_audiobusio_i2sout_stop(self); + mp_raise_RuntimeError(translate("No DMA channel found")); + } else if (result == AUDIO_DMA_MEMORY_ERROR) { + // common_hal_audiobusio_i2sout_stop(self); + mp_raise_RuntimeError(translate("Unable to allocate buffers for signed conversion")); + } + + // OK! We got all of the resources we need and dma is ready. + self->pacing_timer = pacing_timer; + + // Playback with two independent clocks. One is the sample rate which + // determines when we push a new sample to the PWM slice. The second is the + // PWM frequency itself. + + // Determine the DMA divisor. The RP2040 has four pacing timers we can use + // to trigger the DMA. Each has a 16 bit fractional divisor system clock * X / Y where X and Y + // are 16-bit. + + uint32_t sample_rate = audiosample_sample_rate(sample); + uint32_t system_clock = common_hal_mcu_processor_get_frequency(); + uint32_t best_numerator = 0; + uint32_t best_denominator = 0; + uint32_t best_error = system_clock; + + for (uint32_t denominator = 0xffff; denominator > 0; denominator--) { + uint32_t numerator = (denominator * sample_rate) / system_clock; + uint32_t remainder = (denominator * sample_rate) % system_clock; + if (remainder > (system_clock / 2)) { + numerator += 1; + remainder = system_clock - remainder; + } + if (remainder < best_error) { + best_denominator = denominator; + best_numerator = numerator; + best_error = remainder; + // Stop early if we can't do better. + if (remainder == 0) { + break; + } + } + } + + dma_hw->timer[pacing_timer] = best_numerator << 16 | best_denominator; +} + +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 playing = audio_dma_get_playing(&self->dma); + if (!playing && self->pacing_timer < NUM_DMA_TIMERS) { + dma_hw->timer[self->pacing_timer] = 0; + self->pacing_timer = NUM_DMA_TIMERS; + } + return playing; +} + +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) { + audio_dma_resume(&self->dma); +} + +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/audiopwmio/PWMAudioOut.h b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.h new file mode 100644 index 0000000000000..2b43b8354d1ae --- /dev/null +++ b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.h @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOPWMIO_PWMAUDIOOUT_H +#define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOPWMIO_PWMAUDIOOUT_H + +#include "common-hal/pwmio/PWMOut.h" + +#include "audio_dma.h" + +typedef struct { + mp_obj_base_t base; + pwmio_pwmout_obj_t left_pwm; + pwmio_pwmout_obj_t right_pwm; + audio_dma_t dma; + uint16_t quiescent_value; + uint8_t pacing_timer; +} audiopwmio_pwmaudioout_obj_t; + +void audiopwmout_reset(void); + +void audiopwmout_background(void); + +#endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_AUDIOPWMIO_PWMAUDIOOUT_H diff --git a/ports/raspberrypi/common-hal/audiopwmio/__init__.c b/ports/raspberrypi/common-hal/audiopwmio/__init__.c new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/raspberrypi/common-hal/busio/I2C.c b/ports/raspberrypi/common-hal/busio/I2C.c index fa49e375e2da9..0190959f8706c 100644 --- a/ports/raspberrypi/common-hal/busio/I2C.c +++ b/ports/raspberrypi/common-hal/busio/I2C.c @@ -24,12 +24,13 @@ * THE SOFTWARE. */ -#include "shared-bindings/busio/I2C.h" #include "py/mperrno.h" +#include "py/mphal.h" +#include "shared-bindings/busio/I2C.h" #include "py/runtime.h" #include "shared-bindings/microcontroller/__init__.h" -#include "supervisor/shared/translate.h" +#include "shared-bindings/bitbangio/I2C.h" #include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" @@ -37,8 +38,11 @@ #define NO_PIN 0xff +// One second +#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++) { @@ -51,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. @@ -69,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); @@ -90,19 +94,32 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, if (!gpio_get(sda->number) || !gpio_get(scl->number)) { reset_pin_number(sda->number); reset_pin_number(scl->number); - mp_raise_RuntimeError(translate("SDA or SCL needs a pull up")); + mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); } -#endif - - gpio_set_function(sda->number, GPIO_FUNC_I2C); - gpio_set_function(scl->number, GPIO_FUNC_I2C); + #endif + + // Create a bitbangio.I2C object to do 0 byte writes. + // + // These are used to non-invasively detect I2C devices by sending + // the address and confirming an ACK. + // They are not supported by the RP2040 hardware. + // + // Must be done before setting up the I2C pins, since they will be + // set up as GPIO by the bitbangio.I2C object. + // + // Sets pins to open drain, high, and input. + shared_module_bitbangio_i2c_construct(&self->bitbangio_i2c, scl, sda, + frequency, timeout); self->baudrate = i2c_init(self->peripheral, frequency); - self->sda_pin = sda->number; self->scl_pin = scl->number; - claim_pin(sda); + self->sda_pin = sda->number; claim_pin(scl); + claim_pin(sda); + + gpio_set_function(self->scl_pin, GPIO_FUNC_I2C); + gpio_set_function(self->sda_pin, GPIO_FUNC_I2C); } bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { @@ -124,8 +141,7 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { } bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { - uint8_t fake_read = 0; - return i2c_read_blocking(self->peripheral, addr, &fake_read, 1, false) != PICO_ERROR_GENERIC; + return common_hal_busio_i2c_write(self, addr, NULL, 0, true) == 0; } bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { @@ -147,24 +163,56 @@ 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) { - int result = i2c_write_blocking(self->peripheral, addr, data, len, !transmit_stop_bit); + if (len == 0) { + // The RP2040 I2C peripheral will not perform 0 byte writes. + // So use bitbangio.I2C to do the write. + + gpio_set_function(self->scl_pin, GPIO_FUNC_SIO); + gpio_set_function(self->sda_pin, GPIO_FUNC_SIO); + gpio_set_dir(self->scl_pin, GPIO_IN); + gpio_set_dir(self->sda_pin, GPIO_IN); + gpio_put(self->scl_pin, false); + gpio_put(self->sda_pin, false); + + uint8_t status = shared_module_bitbangio_i2c_write(&self->bitbangio_i2c, + 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. + gpio_set_function(self->scl_pin, GPIO_FUNC_I2C); + gpio_set_function(self->sda_pin, GPIO_FUNC_I2C); + + return status; + } + + int result = i2c_write_timeout_us(self->peripheral, addr, data, len, !transmit_stop_bit, BUS_TIMEOUT_US); if (result == len) { return 0; - } else if (result == PICO_ERROR_GENERIC) { - return MP_ENODEV; } - return MP_EIO; + switch (result) { + case PICO_ERROR_GENERIC: + return MP_ENODEV; + case PICO_ERROR_TIMEOUT: + return MP_ETIMEDOUT; + default: + return MP_EIO; + } } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { - int result = i2c_read_blocking(self->peripheral, addr, data, len, false); + 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; - } else if (result == PICO_ERROR_GENERIC) { - return MP_ENODEV; } - return MP_EIO; + switch (result) { + case PICO_ERROR_GENERIC: + return MP_ENODEV; + case PICO_ERROR_TIMEOUT: + return MP_ETIMEDOUT; + default: + return MP_EIO; + } } void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { diff --git a/ports/raspberrypi/common-hal/busio/I2C.h b/ports/raspberrypi/common-hal/busio/I2C.h index d09f29e54cb0e..dbaede1f562d7 100644 --- a/ports/raspberrypi/common-hal/busio/I2C.h +++ b/ports/raspberrypi/common-hal/busio/I2C.h @@ -28,6 +28,7 @@ #define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_BUSIO_I2C_H #include "common-hal/microcontroller/Pin.h" +#include "shared-module/bitbangio/I2C.h" #include "py/obj.h" @@ -35,7 +36,8 @@ 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; uint8_t scl_pin; diff --git a/ports/raspberrypi/common-hal/busio/SPI.c b/ports/raspberrypi/common-hal/busio/SPI.c index b157ae3eb045e..0fc71136e64cf 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 981db46d41dd2..b76dbbf9dbd72 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 f9a75b4996885..e7ba64b098015 100644 --- a/ports/raspberrypi/common-hal/busio/UART.c +++ b/ports/raspberrypi/common-hal/busio/UART.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * Copyright (c) 2021 microDev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,238 +24,185 @@ * THE SOFTWARE. */ -#include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/busio/UART.h" -#include "mpconfigport.h" -#include "lib/utils/interrupt_char.h" -#include "py/gc.h" +#include "py/stream.h" #include "py/mperrno.h" #include "py/runtime.h" -#include "py/stream.h" -#include "supervisor/shared/translate.h" #include "supervisor/shared/tick.h" +#include "lib/utils/interrupt_char.h" +#include "common-hal/microcontroller/Pin.h" -#define UART_DEBUG(...) (void)0 -// #define UART_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) - -// Do-nothing callback needed so that usart_async code will enable rx interrupts. -// See comment below re usart_async_register_callback() -// static void usart_async_rxc_callback(const struct usart_async_descriptor *const descr) { -// // Nothing needs to be done by us. -// } +#include "src/rp2_common/hardware_irq/include/hardware/irq.h" +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" #define NO_PIN 0xff +#define UART_INST(uart) (((uart) ? uart1 : uart0)) + +typedef enum { + STATUS_FREE = 0, + STATUS_BUSY, + STATUS_NEVER_RESET +} uart_status_t; + +static uart_status_t uart_status[NUM_UARTS]; + +void reset_uart(void) { + for (uint8_t num = 0; num < NUM_UARTS; num++) { + if (uart_status[num] == STATUS_BUSY) { + uart_status[num] = STATUS_FREE; + uart_deinit(UART_INST(num)); + } + } +} + +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) { + if (pin == NULL) { + return NO_PIN; + } + if (!(((pin->number % 4) == pin_type) && ((((pin->number + 4) / 8) % NUM_UARTS) == uart))) { + mp_raise_ValueError(translate("Invalid pins")); + } + claim_pin(pin); + gpio_set_function(pin->number, GPIO_FUNC_UART); + return pin->number; +} + +static busio_uart_obj_t *active_uarts[NUM_UARTS]; + +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); + } +} + +static void shared_callback(busio_uart_obj_t *self) { + _copy_into_ringbuf(&self->ringbuf, self->uart); + // We always clear the interrupt so it doesn't continue to fire because we + // may not have read everything available. + uart_get_hw(self->uart)->icr = UART_UARTICR_RXIC_BITS; +} + +static void uart0_callback(void) { + shared_callback(active_uarts[0]); +} + +static void uart1_callback(void) { + shared_callback(active_uarts[1]); +} + 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) { - mp_raise_NotImplementedError(translate("UART not yet supported")); - -// Sercom* sercom = NULL; -// uint8_t sercom_index = 255; // Unset index -// uint32_t rx_pinmux = 0; -// uint8_t rx_pad = 255; // Unset pad -// uint32_t tx_pinmux = 0; -// uint8_t tx_pad = 255; // Unset pad - -// if ((rts != NULL) || (cts != NULL) || (rs485_dir != NULL) || (rs485_invert)) { -// mp_raise_ValueError(translate("RTS/CTS/RS485 Not yet supported on this device")); -// } - -// if (bits > 8) { -// mp_raise_NotImplementedError(translate("bytes > 8 bits not supported")); -// } - -// bool have_tx = tx != NULL; -// bool have_rx = rx != NULL; -// if (!have_tx && !have_rx) { -// mp_raise_ValueError(translate("tx and rx cannot both be None")); -// } - -// self->baudrate = baudrate; -// self->character_bits = bits; -// self->timeout_ms = timeout * 1000; - -// // This assignment is only here because the usart_async routines take a *const argument. -// struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - -// for (int i = 0; i < NUM_SERCOMS_PER_PIN; i++) { -// Sercom* potential_sercom = NULL; -// if (have_tx) { -// sercom_index = tx->sercom[i].index; -// if (sercom_index >= SERCOM_INST_NUM) { -// continue; -// } -// potential_sercom = sercom_insts[sercom_index]; -// #ifdef SAMD21 -// if (potential_sercom->USART.CTRLA.bit.ENABLE != 0 || -// !(tx->sercom[i].pad == 0 || -// tx->sercom[i].pad == 2)) { -// continue; -// } -// #endif -// #ifdef SAM_D5X_E5X -// if (potential_sercom->USART.CTRLA.bit.ENABLE != 0 || -// !(tx->sercom[i].pad == 0)) { -// continue; -// } -// #endif -// tx_pinmux = PINMUX(tx->number, (i == 0) ? MUX_C : MUX_D); -// tx_pad = tx->sercom[i].pad; -// if (rx == NULL) { -// sercom = potential_sercom; -// break; -// } -// } -// for (int j = 0; j < NUM_SERCOMS_PER_PIN; j++) { -// if (((!have_tx && rx->sercom[j].index < SERCOM_INST_NUM && -// sercom_insts[rx->sercom[j].index]->USART.CTRLA.bit.ENABLE == 0) || -// sercom_index == rx->sercom[j].index) && -// rx->sercom[j].pad != tx_pad) { -// rx_pinmux = PINMUX(rx->number, (j == 0) ? MUX_C : MUX_D); -// rx_pad = rx->sercom[j].pad; -// sercom = sercom_insts[rx->sercom[j].index]; -// sercom_index = rx->sercom[j].index; -// break; -// } -// } -// if (sercom != NULL) { -// break; -// } -// } -// if (sercom == NULL) { -// mp_raise_ValueError(translate("Invalid pins")); -// } -// if (!have_tx) { -// tx_pad = 0; -// if (rx_pad == 0) { -// tx_pad = 2; -// } -// } -// if (!have_rx) { -// rx_pad = (tx_pad + 1) % 4; -// } - -// // Set up clocks on SERCOM. -// samd_peripherals_sercom_clock_init(sercom, sercom_index); - -// if (rx && receiver_buffer_size > 0) { -// self->buffer_length = receiver_buffer_size; -// // 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 -// // self->buffer, so do it manually. (However, as long as internal -// // pointers like this are NOT moved, allocating the buffer -// // in the long-lived pool is not strictly necessary) -// self->buffer = (uint8_t *) gc_alloc(self->buffer_length * sizeof(uint8_t), false, true); -// if (self->buffer == NULL) { -// common_hal_busio_uart_deinit(self); -// mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), self->buffer_length * sizeof(uint8_t)); -// } -// } else { -// self->buffer_length = 0; -// self->buffer = NULL; -// } - -// if (usart_async_init(usart_desc_p, sercom, self->buffer, self->buffer_length, NULL) != ERR_NONE) { -// mp_raise_ValueError(translate("Could not initialize UART")); -// } - -// // usart_async_init() sets a number of defaults based on a prototypical SERCOM -// // which don't necessarily match what we need. After calling it, set the values -// // specific to this instantiation of UART. - -// // Set pads computed for this SERCOM. -// // TXPO: -// // 0x0: TX pad 0; no RTS/CTS -// // 0x1: TX pad 2; no RTS/CTS -// // 0x2: TX pad 0; RTS: pad 2, CTS: pad 3 (not used by us right now) -// // So divide by 2 to map pad to value. -// // RXPO: -// // 0x0: RX pad 0 -// // 0x1: RX pad 1 -// // 0x2: RX pad 2 -// // 0x3: RX pad 3 - -// // Doing a group mask and set of the registers saves 60 bytes over setting the bitfields individually. - -// sercom->USART.CTRLA.reg &= ~(SERCOM_USART_CTRLA_TXPO_Msk | -// SERCOM_USART_CTRLA_RXPO_Msk | -// SERCOM_USART_CTRLA_FORM_Msk); -// sercom->USART.CTRLA.reg |= SERCOM_USART_CTRLA_TXPO(tx_pad / 2) | -// SERCOM_USART_CTRLA_RXPO(rx_pad) | -// (parity == BUSIO_UART_PARITY_NONE ? 0 : SERCOM_USART_CTRLA_FORM(1)); - -// // Enable tx and/or rx based on whether the pins were specified. -// // CHSIZE is 0 for 8 bits, 5, 6, 7 for 5, 6, 7 bits. 1 for 9 bits, but we don't support that. -// sercom->USART.CTRLB.reg &= ~(SERCOM_USART_CTRLB_TXEN | -// SERCOM_USART_CTRLB_RXEN | -// SERCOM_USART_CTRLB_PMODE | -// SERCOM_USART_CTRLB_SBMODE | -// SERCOM_USART_CTRLB_CHSIZE_Msk); -// sercom->USART.CTRLB.reg |= (have_tx ? SERCOM_USART_CTRLB_TXEN : 0) | -// (have_rx ? SERCOM_USART_CTRLB_RXEN : 0) | -// (parity == BUSIO_UART_PARITY_ODD ? SERCOM_USART_CTRLB_PMODE : 0) | -// (stop > 1 ? SERCOM_USART_CTRLB_SBMODE : 0) | -// SERCOM_USART_CTRLB_CHSIZE(bits % 8); - -// // Set baud rate -// common_hal_busio_uart_set_baudrate(self, baudrate); - -// // Turn on rx interrupt handling. The UART async driver has its own set of internal callbacks, -// // which are set up by uart_async_init(). These in turn can call user-specified callbacks. -// // In fact, the actual interrupts are not enabled unless we set up a user-specified callback. -// // This is confusing. It's explained in the Atmel START User Guide -> Implementation Description -> -// // Different read function behavior in some asynchronous drivers. As of this writing: -// // http://start.atmel.com/static/help/index.html?GUID-79201A5A-226F-4FBB-B0B8-AB0BE0554836 -// // Look at the ASFv4 code example for async USART. -// usart_async_register_callback(usart_desc_p, USART_ASYNC_RXC_CB, usart_async_rxc_callback); - - -// if (have_tx) { -// gpio_set_pin_direction(tx->number, GPIO_DIRECTION_OUT); -// gpio_set_pin_pull_mode(tx->number, GPIO_PULL_OFF); -// gpio_set_pin_function(tx->number, tx_pinmux); -// self->tx_pin = tx->number; -// claim_pin(tx); -// } else { -// self->tx_pin = NO_PIN; -// } - -// if (have_rx) { -// gpio_set_pin_direction(rx->number, GPIO_DIRECTION_IN); -// gpio_set_pin_pull_mode(rx->number, GPIO_PULL_OFF); -// gpio_set_pin_function(rx->number, rx_pinmux); -// self->rx_pin = rx->number; -// claim_pin(rx); -// } else { -// self->rx_pin = NO_PIN; -// } - -// usart_async_enable(usart_desc_p); + + if (bits > 8) { + mp_raise_ValueError(translate("Invalid word/bit length")); + } + + if (receiver_buffer_size == 0) { + mp_raise_ValueError(translate("Invalid buffer size")); + } + + if ((rs485_dir != NULL) || (rs485_invert)) { + mp_raise_NotImplementedError(translate("RS485 Not yet supported on this device")); + } + + uint8_t uart_id = ((((tx != NULL) ? tx->number : rx->number) + 4) / 8) % NUM_UARTS; + + if (uart_status[uart_id] != STATUS_FREE) { + mp_raise_RuntimeError(translate("All UART peripherals are in use")); + } else { + uart_status[uart_id] = STATUS_BUSY; + } + + self->tx_pin = pin_init(uart_id, tx, 0); + self->rx_pin = pin_init(uart_id, rx, 1); + self->cts_pin = pin_init(uart_id, cts, 2); + self->rts_pin = pin_init(uart_id, rts, 3); + + self->uart = UART_INST(uart_id); + self->uart_id = uart_id; + self->baudrate = baudrate; + self->timeout_ms = timeout * 1000; + + uart_init(self->uart, self->baudrate); + uart_set_fifo_enabled(self->uart, true); + uart_set_format(self->uart, bits, stop, parity); + uart_set_hw_flow(self->uart, (cts != NULL), (rts != 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 + // self->buffer, so do it manually. (However, as long as internal + // pointers like this are NOT moved, allocating the buffer + // in the long-lived pool is not strictly necessary) + // (This is a macro.) + if (!ringbuf_alloc(&self->ringbuf, receiver_buffer_size, true)) { + mp_raise_msg(&mp_type_MemoryError, translate("Failed to allocate RX buffer")); + } + active_uarts[uart_id] = self; + if (uart_id == 1) { + self->uart_irq_id = UART1_IRQ; + irq_set_exclusive_handler(self->uart_irq_id, uart1_callback); + } else { + self->uart_irq_id = UART0_IRQ; + irq_set_exclusive_handler(self->uart_irq_id, uart0_callback); + } + irq_set_enabled(self->uart_irq_id, true); + uart_set_irq_enables(self->uart, true /* rx has data */, false /* tx needs data */); + } } bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { - return self->rx_pin == NO_PIN && self->tx_pin == NO_PIN; + return self->tx_pin == NO_PIN && self->rx_pin == NO_PIN; } void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { if (common_hal_busio_uart_deinited(self)) { return; } - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // usart_async_disable(usart_desc_p); - // usart_async_deinit(usart_desc_p); - reset_pin_number(self->rx_pin); + uart_deinit(self->uart); + ringbuf_free(&self->ringbuf); + active_uarts[self->uart_id] = NULL; + uart_status[self->uart_id] = STATUS_FREE; reset_pin_number(self->tx_pin); - self->rx_pin = NO_PIN; + reset_pin_number(self->rx_pin); + reset_pin_number(self->cts_pin); + reset_pin_number(self->rts_pin); self->tx_pin = NO_PIN; + self->rx_pin = NO_PIN; + self->cts_pin = NO_PIN; + self->rts_pin = NO_PIN; +} + +// Write characters. +size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { + if (self->tx_pin == NO_PIN) { + mp_raise_ValueError(translate("No TX pin")); + } + + size_t left_to_write = len; + while (left_to_write > 0) { + while (uart_is_writable(self->uart) && left_to_write > 0) { + // Write and advance. + uart_get_hw(self->uart)->dr = *data++; + // Decrease how many chars left to write. + left_to_write--; + } + RUN_BACKGROUND_TASKS; + } + + return len; } // Read characters. @@ -264,87 +211,56 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t mp_raise_ValueError(translate("No RX pin")); } - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - if (len == 0) { // Nothing to read. return 0; } - // struct io_descriptor *io; - // usart_async_get_io_descriptor(usart_desc_p, &io); - - size_t total_read = 0; - // uint64_t start_ticks = supervisor_ticks_ms64(); - - // // Busy-wait until timeout or until we've read enough chars. - // while (supervisor_ticks_ms64() - start_ticks <= self->timeout_ms) { - // // Read as many chars as we can right now, up to len. - // size_t num_read = io_read(io, data, len); - - // // Advance pointer in data buffer, and decrease how many chars left to read. - // data += num_read; - // len -= num_read; - // total_read += num_read; - // if (len == 0) { - // // Don't need to read any more: data buf is full. - // break; - // } - // if (num_read > 0) { - // // Reset the timeout on every character read. - // start_ticks = supervisor_ticks_ms64(); - // } - // RUN_BACKGROUND_TASKS; - // // Allow user to break out of a timeout with a KeyboardInterrupt. - // if (mp_hal_is_interrupted()) { - // break; - // } - // // If we are zero timeout, make sure we don't loop again (in the event - // // we read in under 1ms) - // if (self->timeout_ms == 0) { - // break; - // } - // } - - // if (total_read == 0) { - // *errcode = EAGAIN; - // return MP_STREAM_ERROR; - // } + // Prevent conflict with uart irq. + irq_set_enabled(self->uart_irq_id, false); + + // Copy as much received data as available, up to len bytes. + size_t total_read = ringbuf_get_n(&self->ringbuf, data, len); + + // Check if we still need to read more data. + if (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)) { + if (uart_is_readable(self->uart)) { + // Read and advance. + data[total_read] = uart_get_hw(self->uart)->dr; + + // Adjust the counters. + len--; + total_read++; + + // Reset the timeout on every character read. + start_ticks = supervisor_ticks_ms64(); + } + RUN_BACKGROUND_TASKS; + // Allow user to break out of a timeout with a KeyboardInterrupt. + if (mp_hal_is_interrupted()) { + break; + } + } + } - return total_read; -} + // Now that we've emptied the ringbuf some, fill it up with anything in the + // FIFO. This ensures that we'll empty the FIFO as much as possible and + // reset the interrupt when we catch up. + _copy_into_ringbuf(&self->ringbuf, self->uart); -// Write characters. -size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { - if (self->tx_pin == NO_PIN) { - mp_raise_ValueError(translate("No TX pin")); - } + // Re-enable irq. + irq_set_enabled(self->uart_irq_id, true); - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - - // struct io_descriptor *io; - // usart_async_get_io_descriptor(usart_desc_p, &io); - - // // Start writing characters. This is non-blocking and will - // // return immediately after setting up the write. - // if (io_write(io, data, len) < 0) { - // *errcode = MP_EAGAIN; - // return MP_STREAM_ERROR; - // } - - // // Busy-wait until all characters transmitted. - // struct usart_async_status async_status; - // while (true) { - // usart_async_get_status(usart_desc_p, &async_status); - // if (async_status.txcnt >= len) { - // break; - // } - // RUN_BACKGROUND_TASKS; - // } + if (total_read == 0) { + *errcode = EAGAIN; + return MP_STREAM_ERROR; + } - return len; + return total_read; } uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { @@ -352,22 +268,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) { - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // usart_async_set_baud_rate(usart_desc_p, - // // Samples and ARITHMETIC vs FRACTIONAL must correspond to USART_SAMPR in - // // hpl_sercom_config.h. - // _usart_async_calculate_baud_rate(baudrate, // e.g. 9600 baud - // PROTOTYPE_SERCOM_USART_ASYNC_CLOCK_FREQUENCY, - // 16, // samples - // USART_BAUDRATE_ASYNCH_ARITHMETIC, - // 0 // fraction - not used for ARITHMETIC - // )); self->baudrate = baudrate; + uart_set_baudrate(self->uart, baudrate); } 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) { @@ -375,30 +281,30 @@ void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeou } uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self) { - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // struct usart_async_status async_status; - // usart_async_get_status(usart_desc_p, &async_status); - // return async_status.rxcnt; - return 0; + // Prevent conflict with uart irq. + irq_set_enabled(self->uart_irq_id, false); + // The UART only interrupts after a threshold so make sure to copy anything + // out of its FIFO before measuring how many bytes we've received. + _copy_into_ringbuf(&self->ringbuf, self->uart); + irq_set_enabled(self->uart_irq_id, false); + return ringbuf_num_filled(&self->ringbuf); } void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { - // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // usart_async_flush_rx_buffer(usart_desc_p); + // Prevent conflict with uart irq. + irq_set_enabled(self->uart_irq_id, false); + ringbuf_clear(&self->ringbuf); + // Throw away the FIFO contents too. + while (uart_is_readable(self->uart)) { + (void)uart_get_hw(self->uart)->dr; + } + irq_set_enabled(self->uart_irq_id, true); } -// True if there are no characters still to be written. bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { if (self->tx_pin == NO_PIN) { return false; } - return false; - // // This assignment is only here because the usart_async routines take a *const argument. - // struct usart_async_descriptor * const usart_desc_p = (struct usart_async_descriptor * const) &self->usart_desc; - // struct usart_async_status async_status; - // usart_async_get_status(usart_desc_p, &async_status); - // return !(async_status.flags & USART_ASYNC_STATUS_BUSY); + return uart_is_writable(self->uart); } diff --git a/ports/raspberrypi/common-hal/busio/UART.h b/ports/raspberrypi/common-hal/busio/UART.h index 43ed9bee014c7..f6978fd1d249c 100644 --- a/ports/raspberrypi/common-hal/busio/UART.h +++ b/ports/raspberrypi/common-hal/busio/UART.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * Copyright (c) 2021 microDev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -27,21 +27,26 @@ #ifndef MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_BUSIO_UART_H #define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_BUSIO_UART_H -#include "common-hal/microcontroller/Pin.h" - #include "py/obj.h" +#include "py/ringbuf.h" + +#include "src/rp2_common/hardware_uart/include/hardware/uart.h" typedef struct { mp_obj_base_t base; - // struct usart_async_descriptor usart_desc; - uint8_t rx_pin; uint8_t tx_pin; - uint8_t character_bits; - bool rx_error; + uint8_t rx_pin; + uint8_t cts_pin; + uint8_t rts_pin; + uint8_t uart_id; + uint8_t uart_irq_id; uint32_t baudrate; uint32_t timeout_ms; - uint32_t buffer_length; - uint8_t* buffer; + uart_inst_t *uart; + ringbuf_t ringbuf; } busio_uart_obj_t; +extern void reset_uart(void); +extern void never_reset_uart(uint8_t num); + #endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_BUSIO_UART_H diff --git a/ports/raspberrypi/common-hal/countio/Counter.c b/ports/raspberrypi/common-hal/countio/Counter.c new file mode 100644 index 0000000000000..2dcd1de123e7f --- /dev/null +++ b/ports/raspberrypi/common-hal/countio/Counter.c @@ -0,0 +1,103 @@ +#include "common-hal/countio/Counter.h" + +#include "py/runtime.h" +#include "py/mpstate.h" +#include "supervisor/shared/translate.h" + +#include "common-hal/pwmio/PWMOut.h" + +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" +#include "src/rp2_common/hardware_pwm/include/hardware/pwm.h" +#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) { + + if (pwm_gpio_to_channel(pin_a->number) != PWM_CHAN_B) { + mp_raise_RuntimeError(translate("Pin must be on PWM Channel B")); + } + + self->pin_a = pin_a->number; + self->slice_num = pwm_gpio_to_slice_num(self->pin_a); + + if (MP_STATE_PORT(counting)[self->slice_num] != NULL) { + mp_raise_RuntimeError(translate("PWM slice already in use")); + } + + uint8_t channel = pwm_gpio_to_channel(self->pin_a); + if (!pwmio_claim_slice_channels(self->slice_num)) { + mp_raise_RuntimeError(translate("PWM slice channel A already in use")); + } + + pwm_clear_irq(self->slice_num); + pwm_set_irq_enabled(self->slice_num, true); + irq_set_exclusive_handler(PWM_IRQ_WRAP, counter_interrupt_handler); + irq_set_enabled(PWM_IRQ_WRAP, true); + + pwm_config cfg = pwm_get_default_config(); + pwm_config_set_clkdiv_mode(&cfg, PWM_DIV_B_RISING); + pwm_init(self->slice_num, &cfg, false); + gpio_set_function(self->pin_a, GPIO_FUNC_PWM); + + claim_pin(pin_a); + + MP_STATE_PORT(counting)[self->slice_num] = self; + + self->count = 0; + pwm_set_enabled(self->slice_num, true); +} + +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) { + if (common_hal_countio_counter_deinited(self)) { + return; + } + + pwm_set_enabled(self->slice_num, false); + pwm_set_irq_enabled(self->slice_num, false); + + pwmio_release_slice_channels(self->slice_num); + + reset_pin_number(self->pin_a); + + MP_STATE_PORT(counting)[self->slice_num] = NULL; + self->pin_a = 0; + self->slice_num = 0; +} + +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) { + pwm_set_counter(self->slice_num, 0); + self->count = new_count; +} + +void common_hal_countio_counter_reset(countio_counter_obj_t *self) { + pwm_set_counter(self->slice_num, 0); + self->count = 0; +} + +void counter_interrupt_handler() { + uint32_t mask = pwm_get_irq_status_mask(); + + uint8_t i = 1, pos = 1; + while (!(i & mask)) { + i = i << 1; + ++pos; + } + + 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/Counter.h b/ports/raspberrypi/common-hal/countio/Counter.h new file mode 100644 index 0000000000000..201034cf46f09 --- /dev/null +++ b/ports/raspberrypi/common-hal/countio/Counter.h @@ -0,0 +1,19 @@ + +#ifndef MICROPY_INCLUDED_RASPBERRRYPI_COMMON_HAL_COUNTIO_COUNTER_H +#define MICROPY_INCLUDED_RASPBERRRYPI_COMMON_HAL_COUNTIO_COUNTER_H + +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint8_t pin_a; + uint8_t slice_num; + mp_int_t count; +} countio_counter_obj_t; + + +void counter_interrupt_handler(); + +#endif // MICROPY_INCLUDED_RASPBERRRYPI_COMMON_HAL_COUNTIO_COUNTER_H diff --git a/ports/raspberrypi/common-hal/countio/__init__.c b/ports/raspberrypi/common-hal/countio/__init__.c new file mode 100644 index 0000000000000..d47de33e53c31 --- /dev/null +++ b/ports/raspberrypi/common-hal/countio/__init__.c @@ -0,0 +1 @@ +// No countio module functions diff --git a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c index b0bc1b96e819a..22a61afa3f013 100644 --- a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +++ b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c @@ -37,26 +37,27 @@ #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; self->open_drain = false; + // Set to input. No output value. gpio_init(pin->number); return DIGITALINOUT_OK; } 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; } @@ -65,54 +66,65 @@ 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_set_dir(pin, GPIO_OUT); - // TODO: Turn on "strong" pin driving (more current available). + 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); self->output = true; - common_hal_digitalio_digitalinout_set_drive_mode(self, drive_mode); + self->open_drain = drive_mode == DRIVE_MODE_OPEN_DRAIN; + + // Pin direction is ultimately set in set_value. We don't need to do it here. common_hal_digitalio_digitalinout_set_value(self, value); return DIGITALINOUT_OK; } 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) { - gpio_set_dir(pin, value ? GPIO_IN : GPIO_OUT); + if (self->open_drain && value) { + // If true and open-drain, set the direction -before- setting + // the pin value, to to avoid a high glitch on the pin before + // switching from output to input for open-drain. + gpio_set_dir(pin, GPIO_IN); + gpio_put(pin, value); } else { + // Otherwise set the direction -after- setting the pin value, + // to avoid a glitch which might occur if the old value was + // different and the pin was previously set to input. gpio_put(pin, value); + gpio_set_dir(pin, GPIO_OUT); } } 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; - if (self->open_drain) { - gpio_put(pin, false); - } // True is implemented differently between modes so reset the value to make // sure it's correct for the new mode. if (value) { @@ -122,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 { @@ -131,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 8b14bbad8fefd..d656f607f60e5 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 57b2ffc36bcdb..80dbb13bb754c 100644 --- a/ports/raspberrypi/common-hal/displayio/ParallelBus.c +++ b/ports/raspberrypi/common-hal/displayio/ParallelBus.c @@ -32,37 +32,129 @@ #include "py/runtime.h" #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/microcontroller/__init__.h" +#include "bindings/rp2pio/StateMachine.h" +#include "common-hal/rp2pio/StateMachine.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) { +static const uint16_t parallel_program[] = { +// .side_set 1 +// .wrap_target + 0x6008, // out pins, 8 side 0 + 0xB042 // nop side 1 +// .wrap +}; - mp_raise_NotImplementedError(translate("ParallelBus not yet supported")); - // TODO: Implement with PIO and DMA. +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, uint32_t frequency) { + + uint8_t data_pin = data0->number; + for (uint8_t i = 0; i < 8; i++) { + if (!pin_number_is_free(data_pin + i)) { + mp_raise_ValueError_varg(translate("Bus pin %d is already in use"), i); + } + } + + uint8_t write_pin = write->number; + if (!pin_number_is_free(write_pin)) { + mp_raise_ValueError_varg(translate("Bus pin %d is already in use"), write_pin); + } + + self->command.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->command, command); + common_hal_digitalio_digitalinout_switch_to_output(&self->command, true, DRIVE_MODE_PUSH_PULL); + + self->chip_select.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->chip_select, chip_select); + common_hal_digitalio_digitalinout_switch_to_output(&self->chip_select, true, DRIVE_MODE_PUSH_PULL); + + self->read.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->read, read); + common_hal_digitalio_digitalinout_switch_to_output(&self->read, true, DRIVE_MODE_PUSH_PULL); + + self->data0_pin = data_pin; + self->write = write_pin; + + self->reset.base.type = &mp_type_NoneType; + if (reset != NULL) { + self->reset.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->reset, reset); + common_hal_digitalio_digitalinout_switch_to_output(&self->reset, true, DRIVE_MODE_PUSH_PULL); + never_reset_pin_number(reset->number); + common_hal_displayio_parallelbus_reset(self); + } + + never_reset_pin_number(command->number); + never_reset_pin_number(chip_select->number); + never_reset_pin_number(write_pin); + never_reset_pin_number(read->number); + for (uint8_t i = 0; i < 8; i++) { + never_reset_pin_number(data_pin + i); + } + + common_hal_rp2pio_statemachine_construct(&self->state_machine, + parallel_program, sizeof(parallel_program) / sizeof(parallel_program[0]), + frequency * 2, // frequency multiplied by 2 as 2 PIO instructions + NULL, 0, // init + data0, 8, 0, 255, // first out pin, # out pins + NULL, 0, 0, 0, // first in pin, # in pins + NULL, 0, 0, 0, // first set pin + write, 1, 0, 1, // first sideset pin + 0, // wait gpio pins + true, // exclusive pin usage + true, 8, true, // TX, auto pull every 8 bits. shift left to output msb first + false, // wait for TX stall + false, 32, true // RX setting we don't use + ); + + common_hal_rp2pio_statemachine_never_reset(&self->state_machine); } -void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) { +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t *self) { + common_hal_rp2pio_statemachine_deinit(&self->state_machine); + for (uint8_t i = 0; i < 8; i++) { + reset_pin_number(self->data0_pin + i); + } + + reset_pin_number(self->command.pin->number); + reset_pin_number(self->chip_select.pin->number); + reset_pin_number(self->write); + reset_pin_number(self->read.pin->number); + reset_pin_number(self->reset.pin->number); } bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { - return false; + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); + if (self->reset.base.type == &mp_type_NoneType) { + return false; + } + + common_hal_digitalio_digitalinout_set_value(&self->reset, false); + common_hal_mcu_delay_us(4); + common_hal_digitalio_digitalinout_set_value(&self->reset, true); + return true; } bool common_hal_displayio_parallelbus_bus_free(mp_obj_t obj) { - return false; + return true; } bool common_hal_displayio_parallelbus_begin_transaction(mp_obj_t obj) { - - return false; + 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) { + 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); + common_hal_rp2pio_statemachine_write(&self->state_machine, data, data_length, 1); } void common_hal_displayio_parallelbus_end_transaction(mp_obj_t 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/raspberrypi/common-hal/displayio/ParallelBus.h b/ports/raspberrypi/common-hal/displayio/ParallelBus.h index 45989d9900379..3d83c8fca7f77 100644 --- a/ports/raspberrypi/common-hal/displayio/ParallelBus.h +++ b/ports/raspberrypi/common-hal/displayio/ParallelBus.h @@ -28,9 +28,18 @@ #define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_DISPLAYIO_PARALLELBUS_H #include "common-hal/digitalio/DigitalInOut.h" +#include "bindings/rp2pio/StateMachine.h" +#include "common-hal/rp2pio/StateMachine.h" typedef struct { mp_obj_base_t base; + digitalio_digitalinout_obj_t command; + digitalio_digitalinout_obj_t chip_select; + digitalio_digitalinout_obj_t reset; + digitalio_digitalinout_obj_t read; + uint8_t write; + uint8_t data0_pin; + rp2pio_statemachine_obj_t state_machine; } displayio_parallelbus_obj_t; #endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_DISPLAYIO_PARALLELBUS_H diff --git a/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c new file mode 100644 index 0000000000000..2c91a2fa16c39 --- /dev/null +++ b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c @@ -0,0 +1,135 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "py/runtime.h" + +#include "lib/utils/context_manager_helpers.h" +#include "lib/utils/interrupt_char.h" + +#include "bindings/rp2pio/StateMachine.h" +#include "bindings/rp2pio/__init__.h" +#include "common-hal/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/microcontroller/Processor.h" +#include "shared-bindings/microcontroller/__init__.h" + +#include "src/rp2_common/hardware_pio/include/hardware/pio.h" +#include "src/rp2_common/hardware_pio/include/hardware/pio_instructions.h" + +// Define this to (1), and you can scope the instruction-pointer of the state machine on D26..28 (note the weird encoding though!) +#define DEBUG_STATE_MACHINE (0) +#if DEBUG_STATE_MACHINE +#define SIDE(x) ((x)<<8) +#else +#define SIDE(x) (0) +#endif + +#define _0 SIDE(0b11100) +#define _1 SIDE(0b00000) +#define _2 SIDE(0b10000) +#define _3 SIDE(0b10100) +#define _4 SIDE(0b11000) +#define _5 SIDE(0b10100) + +#define IMAGECAPTURE_CODE(width, pclk, vsync, href) \ + { \ +/* 0 */ pio_encode_wait_gpio(0, vsync) | _0, \ +/* 1 */ pio_encode_wait_gpio(1, vsync) | _1, \ + /* .wrap_target */ \ +/* 2 */ pio_encode_wait_gpio(1, href) | _2, \ +/* 3 */ pio_encode_wait_gpio(1, pclk) | _3, \ +/* 4 */ pio_encode_in(pio_pins, width) | _4, \ +/* 5 */ pio_encode_wait_gpio(0, pclk) | _5, \ + /* .wrap */ \ + } + +void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data_clock, + const mcu_pin_obj_t *vertical_sync, + const mcu_pin_obj_t *horizontal_reference, + int data_count) +{ + + uint16_t imagecapture_code[] = IMAGECAPTURE_CODE(data_count, data_clock->number, vertical_sync->number, horizontal_reference->number); + + common_hal_rp2pio_statemachine_construct(&self->state_machine, + imagecapture_code, MP_ARRAY_SIZE(imagecapture_code), + common_hal_mcu_processor_get_frequency(), // full speed (4 instructions per loop -> max pclk 30MHz @ 120MHz) + 0, 0, // init + NULL, 0, 0, 0, // out pins + data0, data_count, // in pins + 0, 0, // in pulls + NULL, 0, 0, 0, // set pins +#if DEBUG_STATE_MACHINE + &pin_GPIO26, 3, 7, 7, // sideset pins +#else + NULL, 0, 0, 0, // sideset pins +#endif + (1<number) | (1<number) | (1<number), // wait gpio pins + true, // exclusive pin use + false, 32, false, // out settings + false, // wait for txstall + true, 32, true); // in settings + + PIO pio = self->state_machine.pio; + uint8_t pio_index = pio_get_index(pio); + uint sm = self->state_machine.state_machine; + rp2pio_statemachine_set_wrap(&self->state_machine, 2, 5); +} + +void common_hal_imagecapture_parallelimagecapture_deinit(imagecapture_parallelimagecapture_obj_t *self) +{ + if (common_hal_imagecapture_parallelimagecapture_deinited(self)) { + return; + } + return common_hal_rp2pio_statemachine_deinit(&self->state_machine); +} + +bool common_hal_imagecapture_parallelimagecapture_deinited(imagecapture_parallelimagecapture_obj_t *self) +{ + return common_hal_rp2pio_statemachine_deinited(&self->state_machine); +} + +void common_hal_imagecapture_parallelimagecapture_capture(imagecapture_parallelimagecapture_obj_t *self, void *buffer, size_t bufsize) +{ + PIO pio = self->state_machine.pio; + uint sm = self->state_machine.state_machine; + uint8_t offset = rp2pio_statemachine_program_offset(&self->state_machine); + + pio_sm_set_enabled(pio, sm, false); + pio_sm_clear_fifos(pio, sm); + + pio_sm_restart(pio, sm); + pio_sm_exec(pio, sm, pio_encode_jmp(offset)); + pio_sm_set_enabled(pio, sm, true); + + common_hal_rp2pio_statemachine_readinto(&self->state_machine, buffer, bufsize, 4); + + pio_sm_set_enabled(pio, sm, false); +} diff --git a/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.h b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.h new file mode 100644 index 0000000000000..9f5d1ab32f3eb --- /dev/null +++ b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.h @@ -0,0 +1,35 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +#include "common-hal/rp2pio/StateMachine.h" +#include "shared-bindings/imagecapture/ParallelImageCapture.h" + +struct imagecapture_parallelimagecapture_obj { + mp_obj_base_t base; + rp2pio_statemachine_obj_t state_machine; +}; diff --git a/ports/raspberrypi/common-hal/imagecapture/__init__.c b/ports/raspberrypi/common-hal/imagecapture/__init__.c new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/raspberrypi/common-hal/imagecapture/__init__.h b/ports/raspberrypi/common-hal/imagecapture/__init__.h new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/raspberrypi/common-hal/microcontroller/Pin.c b/ports/raspberrypi/common-hal/microcontroller/Pin.c index ca5cf5a045aaa..271966c2fe821 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 07c3211850e37..7da3a2b88b3d7 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/Processor.c b/ports/raspberrypi/common-hal/microcontroller/Processor.c index 0ad3a51e28484..e22286ca3d9e1 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Processor.c +++ b/ports/raspberrypi/common-hal/microcontroller/Processor.c @@ -25,6 +25,7 @@ */ #include +#include #include "py/mphal.h" #include "common-hal/microcontroller/Processor.h" @@ -53,12 +54,9 @@ uint32_t common_hal_mcu_processor_get_frequency(void) { } void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { - // TODO: get the unique id from the flash. The chip itself doesn't have one. - // for (int i=0; i<4; i++) { - // for (int k=0; k<4; k++) { - // raw_id[4 * i + k] = (*(id_addresses[i]) >> k * 8) & 0xff; - // } - // } + pico_unique_board_id_t retrieved_id; + pico_get_unique_board_id(&retrieved_id); + memcpy(raw_id, retrieved_id.id, COMMON_HAL_MCU_PROCESSOR_UID_LENGTH); } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { diff --git a/ports/raspberrypi/common-hal/microcontroller/Processor.h b/ports/raspberrypi/common-hal/microcontroller/Processor.h index b7c86e85068a4..afb43f9bdf8cd 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Processor.h +++ b/ports/raspberrypi/common-hal/microcontroller/Processor.h @@ -27,7 +27,9 @@ #ifndef MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_MICROCONTROLLER_PROCESSOR_H #define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_MICROCONTROLLER_PROCESSOR_H -#define COMMON_HAL_MCU_PROCESSOR_UID_LENGTH 16 +#include "src/rp2_common/pico_unique_id/include/pico/unique_id.h" + +#define COMMON_HAL_MCU_PROCESSOR_UID_LENGTH PICO_UNIQUE_BOARD_ID_SIZE_BYTES #include "py/obj.h" diff --git a/ports/raspberrypi/common-hal/microcontroller/__init__.c b/ports/raspberrypi/common-hal/microcontroller/__init__.c index 85bfc329d35f6..6b5cb9b0d8a1c 100644 --- a/ports/raspberrypi/common-hal/microcontroller/__init__.c +++ b/ports/raspberrypi/common-hal/microcontroller/__init__.c @@ -35,12 +35,16 @@ #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/Processor.h" +#include "supervisor/filesystem.h" +#include "supervisor/port.h" #include "supervisor/shared/safe_mode.h" #include "supervisor/shared/translate.h" #include "src/rp2040/hardware_structs/include/hardware/structs/sio.h" #include "src/rp2_common/hardware_sync/include/hardware/sync.h" +#include "hardware/watchdog.h" + void common_hal_mcu_delay_us(uint32_t delay) { mp_hal_delay_us(delay); } @@ -66,8 +70,11 @@ void common_hal_mcu_enable_interrupts(void) { asm volatile ("cpsie i" : : : "memory"); } +static bool next_reset_to_bootloader = false; + void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { if (runmode == RUNMODE_BOOTLOADER) { + next_reset_to_bootloader = true; } else { } if (runmode == RUNMODE_SAFE_MODE) { @@ -76,6 +83,12 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { } void common_hal_mcu_reset(void) { + filesystem_flush(); + if (next_reset_to_bootloader) { + reset_to_bootloader(); + } else { + reset_cpu(); + } } // The singleton microcontroller.Processor object, bound to microcontroller.cpu @@ -116,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 10462b5a33532..d1d872843457a 100644 --- a/ports/raspberrypi/common-hal/neopixel_write/__init__.c +++ b/ports/raspberrypi/common-hal/neopixel_write/__init__.c @@ -29,6 +29,7 @@ #include "bindings/rp2pio/StateMachine.h" #include "common-hal/rp2pio/StateMachine.h" #include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/digitalio/DigitalInOut.h" #include "supervisor/port.h" @@ -53,27 +54,26 @@ const uint16_t neopixel_program[] = { 0xa142 }; -const uint16_t init_program[] = { - 0xe081 -}; - -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; // TODO: Cache the state machine after we create it once. We'll need a way to // change the pins then though. - uint8_t pin_number = digitalinout->pin->number; + uint32_t pins_we_use = 1 << digitalinout->pin->number; bool ok = rp2pio_statemachine_construct(&state_machine, neopixel_program, sizeof(neopixel_program) / sizeof(neopixel_program[0]), 800000 * 6, // 800 khz * 6 cycles per bit - init_program, 1, - NULL, 1, - NULL, 1, - digitalinout->pin, 1, - digitalinout->pin, 1, - 1 << pin_number, true, false, + NULL, 0, // init program + NULL, 1, // out + NULL, 1, // in + 0, 0, // in pulls + NULL, 1, // set + digitalinout->pin, 1, // sideset + 0, pins_we_use, // initial pin state + pins_we_use, true, false, true, 8, false, // TX, auto pull every 8 bits. shift left to output msb first + true, // Wait for txstall. If we don't, then we'll deinit too quickly. false, 32, true, // RX setting we don't use false); // claim pins if (!ok) { @@ -83,13 +83,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) { + } - common_hal_rp2pio_statemachine_write(&state_machine, pixels, num_bytes); + common_hal_rp2pio_statemachine_write(&state_machine, pixels, num_bytes, 1 /* stride in bytes */); // Use a private deinit of the state machine that doesn't reset the pin. rp2pio_statemachine_deinit(&state_machine, true); + + // 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); + // 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 new file mode 100644 index 0000000000000..94d98d686f37c --- /dev/null +++ b/ports/raspberrypi/common-hal/nvm/ByteArray.c @@ -0,0 +1,102 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 microDev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "common-hal/nvm/ByteArray.h" + +#include + +#include "py/runtime.h" +#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; + +#define RMV_OFFSET(addr) addr - flash_binary_start + +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) { + // 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 + 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) { + // 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 + 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) { + 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) { + uint8_t values_in[len]; + common_hal_nvm_bytearray_get_bytes(self, start_index, len, values_in); + + bool all_ones = true; + for (uint32_t i = 0; i < len; i++) { + if (values_in[i] != UINT8_MAX) { + all_ones = false; + break; + } + } + + if (all_ones) { + uint32_t address = (uint32_t)self->start_address + start_index; + uint32_t offset = address % FLASH_PAGE_SIZE; + uint32_t page_addr = address - offset; + + while (len) { + uint32_t write_len = MIN(len, FLASH_PAGE_SIZE - offset); + write_page(page_addr, offset, write_len, values); + len -= write_len; + values += write_len; + page_addr += FLASH_PAGE_SIZE; + offset = 0; + } + } else { + erase_and_write_sector(start_index, len, values); + } + + return true; +} diff --git a/ports/raspberrypi/common-hal/nvm/ByteArray.h b/ports/raspberrypi/common-hal/nvm/ByteArray.h new file mode 100644 index 0000000000000..4667e6b23122f --- /dev/null +++ b/ports/raspberrypi/common-hal/nvm/ByteArray.h @@ -0,0 +1,38 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 microDev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_NVM_BYTEARRAY_H +#define MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_NVM_BYTEARRAY_H + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint8_t *start_address; + uint32_t len; +} nvm_bytearray_obj_t; + +#endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_NVM_BYTEARRAY_H diff --git a/ports/raspberrypi/common-hal/nvm/__init__.c b/ports/raspberrypi/common-hal/nvm/__init__.c new file mode 100644 index 0000000000000..1b702a1584d2f --- /dev/null +++ b/ports/raspberrypi/common-hal/nvm/__init__.c @@ -0,0 +1 @@ +// No nvm module functions. diff --git a/ports/raspberrypi/common-hal/os/__init__.c b/ports/raspberrypi/common-hal/os/__init__.c index dcbd06e937d3d..3352cef122f6d 100644 --- a/ports/raspberrypi/common-hal/os/__init__.c +++ b/ports/raspberrypi/common-hal/os/__init__.c @@ -30,6 +30,11 @@ #include "py/objtuple.h" #include "py/qstr.h" +#include "extmod/crypto-algorithms/sha256.h" + +#include "hardware/structs/rosc.h" + +#include STATIC const qstr os_uname_info_fields[] = { MP_QSTR_sysname, MP_QSTR_nodename, @@ -51,12 +56,70 @@ 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) { - return false; +// NIST Special Publication 800-90B (draft) recommends several extractors, +// including the SHA hash family and states that if the amount of entropy input +// is twice the number of bits output from them, that output can be considered +// essentially fully random. If every RANDOM_SAFETY_MARGIN bits from +// `rosc_hw->randombit` have at least 1 bit of entropy, then this criterion is met. +// +// This works by seeding the `random_state` with plenty of random bits (SHA256 +// as entropy harvesting function), then using that state it as a counter input +// (SHA256 as a CSPRNG), re-seeding at least every 256 blocks (8kB). +// +// In practice, `PractRand` doesn't detect any gross problems with the output +// random numbers on samples of 1 to 8 megabytes, no matter the setting of +// RANDOM_SAFETY_MARGIN. (it does detect "unusual" results from time to time, +// as it will with any RNG) +#define RANDOM_SAFETY_MARGIN (4) + +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; j < SHA256_BLOCK_SIZE; j++) { + out[j] = rosc_hw->randombit & 1; + for (int k = 0; k < 8; k++) { + out[j] = (out[j] << 1) ^ (rosc_hw->randombit & 1); + } + } + sha256_update(&context, out, SHA256_BLOCK_SIZE); + } + sha256_final(&context, out); +} + +static void get_random_bits(BYTE out[SHA256_BLOCK_SIZE]) { + if (!random_state[0]++) { + seed_random_bits(random_state); + } + CRYAL_SHA256_CTX context; + sha256_init(&context); + sha256_update(&context, random_state, SHA256_BLOCK_SIZE); + sha256_final(&context, out); +} + +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 + 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 + while (length) { + size_t n = MIN(length, SHA256_BLOCK_SIZE); + BYTE sha_buf[SHA256_BLOCK_SIZE]; + get_random_bits(sha_buf); + memcpy(buffer, sha_buf, n); + buffer += n; + length -= n; + } + #if ROSC_POWER_SAVE + rosc_hw->ctrl = old_rosc_ctrl; + #endif + return true; } diff --git a/ports/raspberrypi/common-hal/pulseio/PulseIn.c b/ports/raspberrypi/common-hal/pulseio/PulseIn.c new file mode 100644 index 0000000000000..95e38d6522b41 --- /dev/null +++ b/ports/raspberrypi/common-hal/pulseio/PulseIn.c @@ -0,0 +1,218 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dave Putz for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +#include + +#include "py/runtime.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/pulseio/PulseIn.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "supervisor/shared/translate.h" +#include "bindings/rp2pio/StateMachine.h" +#include "common-hal/pulseio/PulseIn.h" + +pulseio_pulsein_obj_t *save_self; + +#define NO_PIN 0xff +volatile bool last_level; +volatile uint16_t level_count = 0; +volatile uint16_t result = 0; +volatile uint16_t buf_index = 0; + +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) { + + 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)); + } + self->pin = pin->number; + self->maxlen = maxlen; + self->idle_state = idle_state; + self->start = 0; + self->len = 0; + save_self = self; + + bool ok = rp2pio_statemachine_construct(&self->state_machine, + pulsein_program, sizeof(pulsein_program) / sizeof(pulsein_program[0]), + 1000000, + NULL, 0, + NULL, 0, + pin, 1, + 0,0, + NULL, 0, + 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 + + pio_sm_set_enabled(self->state_machine.pio,self->state_machine.state_machine, false); + pio_sm_clear_fifos(self->state_machine.pio,self->state_machine.state_machine); + last_level = self->idle_state; + level_count = 0; + result = 0; + buf_index = 0; + + pio_sm_set_in_pins(self->state_machine.pio,self->state_machine.state_machine,pin->number); + common_hal_rp2pio_statemachine_set_interrupt_handler(&(self->state_machine),&common_hal_pulseio_pulsein_interrupt,NULL,PIO_IRQ0_INTE_SM0_RXNEMPTY_BITS); + + // exec a set pindirs to 0 for input + pio_sm_exec(self->state_machine.pio,self->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); + } else { + pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x20a0); + } + pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, true); +} + +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) { + if (common_hal_pulseio_pulsein_deinited(self)) { + return; + } + pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, false); + common_hal_rp2pio_statemachine_deinit(&self->state_machine); + m_free(self->buffer); + reset_pin_number(self->pin); + self->pin = NO_PIN; +} + +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; + 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++; + } 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++; + } + } + } +// 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); + } +} +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); + } else { + 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_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); + common_hal_mcu_delay_us(225); + } + + // Reconfigure the pin for PIO + gpio_set_function(self->pin, GPIO_FUNC_PIO0); + 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) { + self->start = 0; + self->len = 0; +} + +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); + } + uint16_t value = self->buffer[self->start]; + 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; + } + return value; +} + +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) { + return self->len; +} + +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) { + if (index < 0) { + index += self->len; + } + if (index < 0 || index >= self->len) { + mp_raise_IndexError_varg(translate("%q index out of range"), MP_QSTR_PulseIn); + } + uint16_t value = self->buffer[(self->start + index) % self->maxlen]; + return value; +} diff --git a/ports/raspberrypi/common-hal/pulseio/PulseIn.h b/ports/raspberrypi/common-hal/pulseio/PulseIn.h new file mode 100644 index 0000000000000..b68a2238d5768 --- /dev/null +++ b/ports/raspberrypi/common-hal/pulseio/PulseIn.h @@ -0,0 +1,50 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dave Putz for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEIN_H +#define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEIN_H + +#include "common-hal/microcontroller/Pin.h" +#include "src/rp2_common/hardware_pio/include/hardware/pio.h" +#include "common-hal/rp2pio/StateMachine.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint8_t pin; + uint16_t *buffer; + uint16_t maxlen; + bool idle_state; + volatile uint16_t start; + volatile uint16_t len; + rp2pio_statemachine_obj_t state_machine; +} pulseio_pulsein_obj_t; + +void pulsein_reset(void); +void common_hal_pulseio_pulsein_interrupt(); + +#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEIN_H diff --git a/ports/raspberrypi/common-hal/pulseio/PulseOut.c b/ports/raspberrypi/common-hal/pulseio/PulseOut.c new file mode 100644 index 0000000000000..c3536af04bf6b --- /dev/null +++ b/ports/raspberrypi/common-hal/pulseio/PulseOut.c @@ -0,0 +1,95 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dave Putz for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "common-hal/pulseio/PulseOut.h" + +#include + +#include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" + +#include "mpconfigport.h" +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/pulseio/PulseOut.h" +#include "supervisor/shared/translate.h" + +static uint8_t refcount = 0; + + +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; + +void pulse_finish(void) { + pulse_index++; + + // Always turn it off. + if (pulse_index >= pulse_length) { + return; + } + current_compare = (current_compare + pulse_buffer[pulse_index] * 3 / 4) & 0xffff; +} + +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")); + + refcount++; + + self->pin = carrier->pin->number; + +} + +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) { + if (common_hal_pulseio_pulseout_deinited(self)) { + return; + } + + + refcount--; + self->pin = NO_PIN; +} + +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; + + current_compare = pulses[0] * 3 / 4; + +} diff --git a/ports/raspberrypi/common-hal/pulseio/PulseOut.h b/ports/raspberrypi/common-hal/pulseio/PulseOut.h new file mode 100644 index 0000000000000..4f1bb9fa7a362 --- /dev/null +++ b/ports/raspberrypi/common-hal/pulseio/PulseOut.h @@ -0,0 +1,44 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dave Putz for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEOUT_H +#define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEOUT_H + +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +#define NO_PIN 0xff + +typedef struct { + mp_obj_base_t base; + uint8_t pin; +} pulseio_pulseout_obj_t; + +void pulseout_reset(void); +void pulseout_interrupt_handler(uint8_t index); + +#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PULSEIO_PULSEOUT_H diff --git a/ports/raspberrypi/common-hal/pulseio/__init__.c b/ports/raspberrypi/common-hal/pulseio/__init__.c new file mode 100644 index 0000000000000..2bee925bc77fb --- /dev/null +++ b/ports/raspberrypi/common-hal/pulseio/__init__.c @@ -0,0 +1 @@ +// No pulseio module functions. diff --git a/ports/raspberrypi/common-hal/pwmio/PWMOut.c b/ports/raspberrypi/common-hal/pwmio/PWMOut.c index 567ec5ef54fba..9695a8fdf75a4 100644 --- a/ports/raspberrypi/common-hal/pwmio/PWMOut.c +++ b/ports/raspberrypi/common-hal/pwmio/PWMOut.c @@ -39,24 +39,67 @@ #include "src/rp2_common/hardware_pwm/include/hardware/pwm.h" uint32_t target_slice_frequencies[NUM_PWM_SLICES]; -uint32_t slice_fixed_frequency; +uint32_t slice_variable_frequency; #define CHANNELS_PER_SLICE 2 static uint32_t channel_use; static uint32_t never_reset_channel; +// Per the RP2040 datasheet: +// +// "A CC value of 0 will produce a 0% output, i.e. the output signal +// is always low. A CC value of TOP + 1 (i.e. equal to the period, in +// non-phase-correct mode) will produce a 100% output. For example, if +// TOP is programmed to 254, the counter will have a period of 255 +// cycles, and CC values in the range of 0 to 255 inclusive will +// produce duty cycles in the range 0% to 100% inclusive." +// +// So 65534 should be the maximum top value, and we'll set CC to be TOP+1 as appropriate. +#define MAX_TOP 65534 + static uint32_t _mask(uint8_t slice, uint8_t channel) { return 1 << (slice * CHANNELS_PER_SLICE + channel); } +bool pwmio_claim_slice_channels(uint8_t slice) { + uint32_t channel_use_mask_a = _mask(slice, 0); + uint32_t channel_use_mask_b = _mask(slice, 1); + + if ((channel_use & channel_use_mask_a) != 0) { + return false; + } + if ((channel_use & channel_use_mask_b) != 0) { + return false; + } + + channel_use |= channel_use_mask_a; + channel_use |= channel_use_mask_b; + return true; +} + +void pwmio_release_slice_channels(uint8_t slice) { + uint32_t channel_mask = _mask(slice, 0); + channel_use &= ~channel_mask; + channel_mask = _mask(slice, 1); + channel_use &= ~channel_mask; +} + +void pwmout_never_reset(uint8_t slice, uint8_t channel) { + never_reset_channel |= _mask(slice, channel); +} + +void pwmout_reset_ok(uint8_t slice, uint8_t channel) { + never_reset_channel &= ~_mask(slice, channel); +} + void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - never_reset_channel |= _mask(self->slice, self->channel); + pwmout_never_reset(self->slice, self->channel); never_reset_pin_number(self->pin->number); } void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { - never_reset_channel &= ~_mask(self->slice, self->channel); + pwmout_reset_ok(self->slice, self->channel); } void pwmout_reset(void) { @@ -76,25 +119,11 @@ void pwmout_reset(void) { } pwm_set_enabled(slice, false); target_slice_frequencies[slice] = 0; - slice_fixed_frequency &= ~(1 << slice); + slice_variable_frequency &= ~(1 << slice); } } -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; - - if (frequency == 0 || frequency > (common_hal_mcu_processor_get_frequency() / 2)) { - return PWMOUT_INVALID_FREQUENCY; - } - - uint8_t slice = pwm_gpio_to_slice_num(pin->number); - uint8_t channel = pwm_gpio_to_channel(pin->number); +pwmout_result_t pwmout_allocate(uint8_t slice, uint8_t channel, bool variable_frequency, uint32_t frequency) { uint32_t channel_use_mask = _mask(slice, channel); // Check the channel first. @@ -107,8 +136,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, if (variable_frequency) { return PWMOUT_ALL_TIMERS_ON_PIN_IN_USE; } - // If the other user wants to change frequency then we can't share either. - if ((slice_fixed_frequency & (1 << slice)) != 0) { + // If the other user wants a variable frequency then we can't share either. + if ((slice_variable_frequency & (1 << slice)) != 0) { return PWMOUT_ALL_TIMERS_ON_PIN_IN_USE; } // If we're both fixed frequency but we don't match target frequencies then we can't share. @@ -116,13 +145,39 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, return PWMOUT_ALL_TIMERS_ON_PIN_IN_USE; } } - self->slice = slice; - self->channel = channel; + channel_use |= channel_use_mask; - if (!variable_frequency) { - slice_fixed_frequency |= 1 << slice; + if (variable_frequency) { + slice_variable_frequency |= 1 << slice; } + 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) { + self->pin = pin; + self->variable_frequency = variable_frequency; + self->duty_cycle = duty; + + if (frequency == 0 || frequency > (common_hal_mcu_processor_get_frequency() / 2)) { + return PWMOUT_INVALID_FREQUENCY; + } + + uint8_t slice = pwm_gpio_to_slice_num(pin->number); + uint8_t channel = pwm_gpio_to_channel(pin->number); + + int r = pwmout_allocate(slice, channel, variable_frequency, frequency); + if (r != PWMOUT_OK) { + return r; + } + + self->slice = slice; + self->channel = channel; + if (target_slice_frequencies[slice] != frequency) { // Reset the counter and compare values. pwm_hw->slice[slice].ctr = PWM_CH0_CTR_RESET; @@ -130,6 +185,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, common_hal_pwmio_pwmout_set_frequency(self, frequency); pwm_set_enabled(slice, true); } else { + common_hal_pwmio_pwmout_set_frequency(self, frequency); common_hal_pwmio_pwmout_set_duty_cycle(self, duty); } @@ -139,39 +195,58 @@ 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) { - if (common_hal_pwmio_pwmout_deinited(self)) { - return; - } - uint32_t channel_mask = _mask(self->slice, self->channel); +void pwmout_free(uint8_t slice, uint8_t channel) { + uint32_t channel_mask = _mask(slice, channel); channel_use &= ~channel_mask; never_reset_channel &= ~channel_mask; - uint32_t slice_mask = ((1 << CHANNELS_PER_SLICE) - 1) << (self->slice * CHANNELS_PER_SLICE + self->channel); + uint32_t slice_mask = ((1 << CHANNELS_PER_SLICE) - 1) << (slice * CHANNELS_PER_SLICE); if ((channel_use & slice_mask) == 0) { - target_slice_frequencies[self->slice] = 0; - slice_fixed_frequency &= ~(1 << self->slice); - pwm_set_enabled(self->slice, false); + target_slice_frequencies[slice] = 0; + slice_variable_frequency &= ~(1 << slice); + pwm_set_enabled(slice, false); } +} +void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { + if (common_hal_pwmio_pwmout_deinited(self)) { + return; + } + pwmout_free(self->slice, self->channel); reset_pin_number(self->pin->number); 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; - uint16_t actual_duty = duty * self->top / ((1 << 16) - 1); - pwm_set_chan_level(self->slice, self->channel, actual_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); + } else { + 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 common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t frequency) { +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) { if (frequency == 0 || frequency > (common_hal_mcu_processor_get_frequency() / 2)) { mp_raise_ValueError(translate("Invalid PWM frequency")); } @@ -179,11 +254,11 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t fr target_slice_frequencies[self->slice] = frequency; // For low frequencies use the divider to give us full resolution duty_cycle. - if (frequency < (common_hal_mcu_processor_get_frequency() / (1 << 16))) { + if (frequency <= (common_hal_mcu_processor_get_frequency() / (1 << 16))) { // 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. @@ -193,24 +268,25 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t fr if (div16 >= (1 << 12)) { div16 = (1 << 12) - 1; } - self->actual_frequency = frequency16 / div16; - self->top = 1 << 16; + self->actual_frequency = (frequency16 + (div16 / 2)) / div16; + self->top = MAX_TOP; pwm_set_clkdiv_int_frac(self->slice, div16 / 16, div16 % 16); - pwm_set_wrap(self->slice, self->top - 1); + pwm_set_wrap(self->slice, self->top); } else { uint32_t top = common_hal_mcu_processor_get_frequency() / frequency; self->actual_frequency = common_hal_mcu_processor_get_frequency() / top; - self->top = top; + self->top = MIN(MAX_TOP, top); pwm_set_clkdiv_int_frac(self->slice, 1, 0); - pwm_set_wrap(self->slice, self->top - 1); + // Set TOP register. For 100% duty cycle, CC must be set to TOP+1. + pwm_set_wrap(self->slice, self->top); } 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 50f84777b5101..c7707762e4012 100644 --- a/ports/raspberrypi/common-hal/pwmio/PWMOut.h +++ b/ports/raspberrypi/common-hal/pwmio/PWMOut.h @@ -39,9 +39,20 @@ typedef struct { bool variable_frequency; uint16_t duty_cycle; uint32_t actual_frequency; - uint32_t top; + uint16_t top; } pwmio_pwmout_obj_t; void pwmout_reset(void); +// Private API for AudioPWMOut. +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); +void pwmout_never_reset(uint8_t slice, uint8_t channel); +void pwmout_reset_ok(uint8_t slice, uint8_t channel); + +// Private API for countio to claim both channels on a slice +bool pwmio_claim_slice_channels(uint8_t slice); +void pwmio_release_slice_channels(uint8_t slice); #endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_PWMIO_PWMOUT_H diff --git a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c new file mode 100644 index 0000000000000..f150422e3cf49 --- /dev/null +++ b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c @@ -0,0 +1,70 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/mphal.h" + +#include "common-hal/rgbmatrix/RGBMatrix.h" +#include "shared-bindings/pwmio/PWMOut.h" +#include "shared-module/rgbmatrix/RGBMatrix.h" + +#include "src/rp2_common/hardware_pwm/include/hardware/pwm.h" + +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); + 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 NULL; +} + +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) { + int8_t slice = ((intptr_t)ptr) & 0xff; + pwm_set_enabled(slice, false); +} + +void common_hal_rgbmatrix_timer_free(void *ptr) { + intptr_t value = (intptr_t)ptr; + uint8_t slice = value & 0xff; + uint8_t channel = value >> 8; + pwm_set_enabled(slice, false); + pwmout_free(slice, channel); + return; +} diff --git a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.h b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.h new file mode 100644 index 0000000000000..d14cd9b0836d3 --- /dev/null +++ b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.h @@ -0,0 +1,37 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_RGBMATRIX_RGBMATRIX_H +#define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_RGBMATRIX_RGBMATRIX_H + +#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 *); + +#endif diff --git a/ports/raspberrypi/common-hal/rgbmatrix/__init__.c b/ports/raspberrypi/common-hal/rgbmatrix/__init__.c new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c new file mode 100644 index 0000000000000..c441ea2e84afb --- /dev/null +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c @@ -0,0 +1,131 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/runtime.h" + +#include +#include "common-hal/rotaryio/IncrementalEncoder.h" +#include "shared-module/rotaryio/IncrementalEncoder.h" +#include "bindings/rp2pio/__init__.h" +#include "bindings/rp2pio/StateMachine.h" + +STATIC const uint16_t encoder[] = { + // again: + // in pins, 2 + 0x4002, + // mov x, isr + 0xa026, + // jmp x!=y, push_data + 0x00a5, + // mov isr, null + 0xa0c3, + // jmp again + 0x0000, + // push_data: + // push + 0x8020, + // mov y, x + 0xa041, +}; + +STATIC const uint16_t encoder_init[] = { + // set y, 31 + 0xe05f, +}; + +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) { + mp_obj_t pins[] = {MP_OBJ_FROM_PTR(pin_a), MP_OBJ_FROM_PTR(pin_b)}; + // Start out with swapped to match behavior with other ports. + self->swapped = true; + if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { + pins[0] = MP_OBJ_FROM_PTR(pin_b); + pins[1] = MP_OBJ_FROM_PTR(pin_a); + self->swapped = false; + if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { + mp_raise_RuntimeError(translate("Pins must be sequential")); + } + } + + self->position = 0; + self->quarter_count = 0; + + common_hal_rp2pio_statemachine_construct(&self->state_machine, + encoder, MP_ARRAY_SIZE(encoder), + 1000000, + encoder_init, MP_ARRAY_SIZE(encoder_init), // init + NULL, 0, 0, 0, // out pin + pins[0], 2, // in pins + 3, 0, // in pulls + NULL, 0, 0, 0x1f, // set pins + NULL, 0, 0, 0x1f, // sideset pins + 0, // wait gpio pins + true, // exclusive pin use + false, 32, false, // out settings + false, // Wait for txstall + false, 32, false); // in settings + + common_hal_rp2pio_statemachine_run(&self->state_machine, encoder_init, MP_ARRAY_SIZE(encoder_init)); + + // We're guaranteed by the init code that some output will be available promptly + uint8_t quiescent_state; + common_hal_rp2pio_statemachine_readinto(&self->state_machine, &quiescent_state, 1, 1); + + shared_module_softencoder_state_init(self, quiescent_state & 3); + 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) { + return common_hal_rp2pio_statemachine_deinited(&self->state_machine); +} + +void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t *self) { + if (common_hal_rotaryio_incrementalencoder_deinited(self)) { + return; + } + common_hal_rp2pio_statemachine_set_interrupt_handler(&self->state_machine, NULL, NULL, 0); + common_hal_rp2pio_statemachine_deinit(&self->state_machine); +} + +STATIC void incrementalencoder_interrupt_handler(void *self_in) { + rotaryio_incrementalencoder_obj_t *self = self_in; + + while (common_hal_rp2pio_statemachine_get_in_waiting(&self->state_machine)) { + // Bypass all the logic of StateMachine.c:_transfer, we need something + // very simple and fast for an interrupt! + uint8_t new_state = self->state_machine.pio->rxf[self->state_machine.state_machine]; + if (self->swapped) { + if (new_state == 0x1) { + new_state = 0x2; + } else if (new_state == 0x2) { + new_state = 0x1; + } + } + shared_module_softencoder_state_update(self, new_state); + } +} diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h new file mode 100644 index 0000000000000..6745d95a1c5aa --- /dev/null +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h @@ -0,0 +1,41 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +#include "common-hal/rp2pio/StateMachine.h" +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + rp2pio_statemachine_obj_t state_machine; + uint8_t state; // + int8_t quarter_count; // count intermediate transitions between detents + bool swapped; // Did the pins need to be swapped to be sequential? + mp_int_t position; +} rotaryio_incrementalencoder_obj_t; diff --git a/ports/raspberrypi/common-hal/rotaryio/__init__.c b/ports/raspberrypi/common-hal/rotaryio/__init__.c new file mode 100644 index 0000000000000..0aae79c26a1c7 --- /dev/null +++ b/ports/raspberrypi/common-hal/rotaryio/__init__.c @@ -0,0 +1 @@ +// No rotaryio module functions. diff --git a/ports/raspberrypi/common-hal/rotaryio/__init__.h b/ports/raspberrypi/common-hal/rotaryio/__init__.h new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c index 6510410b0ec33..21ec09c42c0a1 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c @@ -27,6 +27,7 @@ #include "bindings/rp2pio/StateMachine.h" #include "common-hal/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Pin.h" #include "src/rp2040/hardware_regs/include/hardware/platform_defs.h" @@ -34,6 +35,7 @@ #include "src/rp2_common/hardware_dma/include/hardware/dma.h" #include "src/rp2_common/hardware_pio/include/hardware/pio_instructions.h" #include "src/rp2040/hardware_structs/include/hardware/structs/iobank0.h" +#include "src/rp2_common/hardware_irq/include/hardware/irq.h" #include "lib/utils/interrupt_char.h" #include "py/obj.h" @@ -51,10 +53,25 @@ 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 *); +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 < TOTAL_GPIO_COUNT; i++) { + bool used = pins_we_use & (1 << i); + if (used) { + bool pull_up = pull_pin_up & (1 << i); + bool pull_down = pull_pin_down & (1 << i); + gpio_set_pulls(i, pull_up, pull_down); + } + } +} void _reset_statemachine(PIO pio, uint8_t sm, bool leave_pins) { uint8_t pio_index = pio_get_index(pio); - pio_sm_unclaim(pio, sm); uint32_t program_id = _current_program_id[pio_index][sm]; if (program_id == 0) { return; @@ -89,6 +106,8 @@ void _reset_statemachine(PIO pio, uint8_t sm, bool leave_pins) { } } _current_sm_pins[pio_index][sm] = 0; + pio->inte0 &= ~((PIO_IRQ0_INTF_SM0_RXNEMPTY_BITS | PIO_IRQ0_INTF_SM0_TXNFULL_BITS | PIO_IRQ0_INTF_SM0_BITS) << sm); + pio_sm_unclaim(pio, sm); } void reset_rp2pio_statemachine(void) { @@ -101,9 +120,16 @@ void reset_rp2pio_statemachine(void) { _reset_statemachine(pio, j, false); } } + 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++) { @@ -111,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); } @@ -123,27 +149,30 @@ 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 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 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, + 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, + bool wait_for_txstall, 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 + .origin = -1 }; for (size_t i = 0; i < NUM_PIOS; i++) { PIO pio = pio_instances[i]; @@ -193,18 +222,27 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, if (program_offset == 32) { program_offset = pio_add_program(self->pio, &program_struct); } + self->offset = program_offset; _current_program_id[pio_index][state_machine] = program_id; _current_program_len[pio_index][state_machine] = program_len; _current_program_offset[pio_index][state_machine] = program_offset; _current_sm_pins[pio_index][state_machine] = pins_we_use; _current_pins[pio_index] |= pins_we_use; + pio_sm_set_pins_with_mask(self->pio, state_machine, initial_pin_state, pins_we_use); + pio_sm_set_pindirs_with_mask(self->pio, state_machine, initial_pin_direction, pins_we_use); + rp2pio_statemachine_set_pull(pull_pin_up, pull_pin_down, pins_we_use); + self->initial_pin_state = initial_pin_state; + self->initial_pin_direction = initial_pin_direction; + self->pull_pin_up = pull_pin_up; + self->pull_pin_down = pull_pin_down; + for (size_t pin_number = 0; pin_number < TOTAL_GPIO_COUNT; pin_number++) { if ((pins_we_use & (1 << pin_number)) == 0) { 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) { @@ -219,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; @@ -260,31 +298,45 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, self->out = tx_fifo; self->out_shift_right = out_shift_right; self->in_shift_right = in_shift_right; + self->wait_for_txstall = wait_for_txstall; + + self->init = init; + self->init_len = init_len; sm_config_set_fifo_join(&c, join); + self->sm_config = c; pio_sm_init(self->pio, self->state_machine, program_offset, &c); + common_hal_rp2pio_statemachine_run(self, init, init_len); + + common_hal_rp2pio_statemachine_set_frequency(self, frequency); pio_sm_set_enabled(self->pio, self->state_machine, true); - for (size_t i = 0; i < init_len; i++) { - pio_sm_exec(self->pio, self->state_machine, init[i]); - } return true; } +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, - const mcu_pin_obj_t * first_in_pin, uint8_t in_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, + 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, + uint32_t wait_gpio_mask, bool exclusive_pin_use, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, + bool wait_for_txstall, bool auto_push, uint8_t push_threshold, bool in_shift_right) { // First, check that all pins are free OR already in use by any PIO if exclusive_pin_use is false. - uint32_t pins_we_use = 0; + uint32_t pins_we_use = wait_gpio_mask; pins_we_use |= _check_pins_free(first_out_pin, out_pin_count, exclusive_pin_use); pins_we_use |= _check_pins_free(first_in_pin, in_pin_count, exclusive_pin_use); pins_we_use |= _check_pins_free(first_set_pin, set_pin_count, exclusive_pin_use); @@ -397,20 +449,46 @@ void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, mp_raise_ValueError_varg(translate("Program does OUT without loading OSR")); } - if (in_pin_count > 8 || out_pin_count > 8) { - mp_raise_NotImplementedError(translate("Only IN/OUT of up to 8 supported")); + uint32_t initial_pin_state = mask_and_rotate(first_out_pin, out_pin_count, initial_out_pin_state); + uint32_t initial_pin_direction = mask_and_rotate(first_out_pin, out_pin_count, initial_out_pin_direction); + 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); + // 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")); } + if ((initial_pin_direction & set_out_overlap) != (initial_set_pin_direction & set_out_overlap)) { + mp_raise_ValueError(translate("Initial set pin direction conflicts with initial out pin direction")); + } + initial_pin_state |= initial_set_pin_state; + initial_pin_direction |= initial_set_pin_direction; + + // Sideset overrides OUT or SET so we always use its values. + uint32_t sideset_mask = mask_and_rotate(first_sideset_pin, sideset_pin_count, 0x1f); + initial_pin_state = (initial_pin_state & ~sideset_mask) | mask_and_rotate(first_sideset_pin, sideset_pin_count, initial_sideset_pin_state); + initial_pin_direction = (initial_pin_direction & ~sideset_mask) | mask_and_rotate(first_sideset_pin, sideset_pin_count, initial_sideset_pin_direction); + // Deal with pull up/downs + uint32_t pull_up = mask_and_rotate(first_in_pin, in_pin_count, pull_pin_up); + uint32_t pull_down = mask_and_rotate(first_in_pin, in_pin_count, pull_pin_down); + if (initial_pin_direction & (pull_up | pull_down)) { + mp_raise_ValueError(translate("pull masks conflict with direction masks")); + } bool ok = rp2pio_statemachine_construct(self, program, program_len, frequency, init, init_len, first_out_pin, out_pin_count, first_in_pin, in_pin_count, + pull_up, pull_down, first_set_pin, set_pin_count, first_sideset_pin, sideset_pin_count, + initial_pin_state, initial_pin_direction, pins_we_use, tx_fifo, rx_fifo, auto_pull, pull_threshold, out_shift_right, + wait_for_txstall, auto_push, push_threshold, in_shift_right, true /* claim pins */); if (!ok) { @@ -418,13 +496,59 @@ void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, } } -uint32_t common_hal_rp2pio_statemachine_get_frequency(rp2pio_statemachine_obj_t* self) { +void common_hal_rp2pio_statemachine_restart(rp2pio_statemachine_obj_t *self) { + pio_sm_restart(self->pio, self->state_machine); + + uint8_t pio_index = pio_get_index(self->pio); + uint32_t pins_we_use = _current_sm_pins[pio_index][self->state_machine]; + pio_sm_set_pins_with_mask(self->pio, self->state_machine, self->initial_pin_state, pins_we_use); + pio_sm_set_pindirs_with_mask(self->pio, self->state_machine, self->initial_pin_direction, pins_we_use); + rp2pio_statemachine_set_pull(self->pull_pin_up, self->pull_pin_down, pins_we_use); + common_hal_rp2pio_statemachine_run(self, self->init, self->init_len); + pio_sm_set_enabled(self->pio, self->state_machine, true); +} + +void common_hal_rp2pio_statemachine_stop(rp2pio_statemachine_obj_t *self) { + pio_sm_set_enabled(self->pio, self->state_machine, false); +} + +void common_hal_rp2pio_statemachine_run(rp2pio_statemachine_obj_t *self, const uint16_t *instructions, size_t len) { + for (size_t i = 0; i < len; i++) { + pio_sm_exec(self->pio, self->state_machine, instructions[i]); + } +} + +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) { + if (frequency == 0) { + frequency = clock_get_hz(clk_sys); + } + uint64_t frequency256 = ((uint64_t)clock_get_hz(clk_sys)) * 256; + uint64_t div256 = frequency256 / frequency; + if (frequency256 % div256 > 0) { + div256 += 1; + } + // 0 is interpreted as 0x10000 so it's valid. + if (div256 / 256 > 0x10000 || frequency > clock_get_hz(clk_sys)) { + mp_raise_ValueError_varg(translate("%q out of range"), MP_QSTR_frequency); + } + self->actual_frequency = frequency256 / div256; + + pio_sm_set_clkdiv_int_frac(self->pio, self->state_machine, div256 / 256, div256 % 256); + // Reset the clkdiv counter in case our new TOP is lower. + pio_sm_clkdiv_restart(self->pio, self->state_machine); +} + void rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self, bool leave_pins) { uint8_t sm = self->state_machine; uint8_t pio_index = pio_get_index(self->pio); + common_hal_mcu_disable_interrupts(); + _interrupt_arg[pio_index][sm] = NULL; + _interrupt_handler[pio_index][sm] = NULL; + common_hal_mcu_enable_interrupts(); _never_reset[pio_index][sm] = false; _reset_statemachine(self->pio, sm, leave_pins); self->state_machine = NUM_PIO_STATE_MACHINES; @@ -445,9 +569,21 @@ bool common_hal_rp2pio_statemachine_deinited(rp2pio_statemachine_obj_t *self) { return self->state_machine == NUM_PIO_STATE_MACHINES; } +enum dma_channel_transfer_size _stride_to_dma_size(uint8_t stride) { + switch (stride) { + case 4: + return DMA_SIZE_32; + case 2: + return DMA_SIZE_16; + case 1: + default: + return DMA_SIZE_8; + } +} + static bool _transfer(rp2pio_statemachine_obj_t *self, - const uint8_t *data_out, size_t out_len, - uint8_t *data_in, size_t in_len) { + 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) { // This implementation is based on SPI but varies because the tx and rx buffers // may be different lengths and occur at different times or speeds. @@ -467,47 +603,48 @@ 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 += 3; + tx_destination += 4 - out_stride_in_bytes; } } if (rx) { - rx_source = (const volatile uint8_t*) &self->pio->rxf[self->state_machine]; - if (!self->in_shift_right) { - rx_source += 3; + rx_source = (const volatile uint8_t *)&self->pio->rxf[self->state_machine]; + if (self->in_shift_right) { + rx_source += 4 - in_stride_in_bytes; } } + uint32_t stall_mask = 1 << (PIO_FDEBUG_TXSTALL_LSB + self->state_machine); bool use_dma = (!rx || chan_rx >= 0) && (!tx || chan_tx >= 0); if (use_dma) { dma_channel_config c; uint32_t channel_mask = 0; if (tx) { c = dma_channel_get_default_config(chan_tx); - channel_config_set_transfer_data_size(&c, DMA_SIZE_8); + channel_config_set_transfer_data_size(&c, _stride_to_dma_size(out_stride_in_bytes)); channel_config_set_dreq(&c, self->tx_dreq); channel_config_set_read_increment(&c, true); channel_config_set_write_increment(&c, false); dma_channel_configure(chan_tx, &c, tx_destination, data_out, - len, + out_len / out_stride_in_bytes, false); channel_mask |= 1u << chan_tx; } if (rx) { c = dma_channel_get_default_config(chan_rx); - channel_config_set_transfer_data_size(&c, DMA_SIZE_8); + channel_config_set_transfer_data_size(&c, _stride_to_dma_size(in_stride_in_bytes)); channel_config_set_dreq(&c, self->rx_dreq); channel_config_set_read_increment(&c, false); channel_config_set_write_increment(&c, true); dma_channel_configure(chan_rx, &c, data_in, rx_source, - len, + in_len / in_stride_in_bytes, false); channel_mask |= 1u << chan_rx; } @@ -528,7 +665,7 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, } } // Clear the stall bit so we can detect when the state machine is done transmitting. - self->pio->fdebug = PIO_FDEBUG_TXSTALL_BITS; + self->pio->fdebug = stall_mask; } // If we have claimed only one channel successfully, we should release immediately. This also @@ -542,18 +679,30 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, if (!use_dma && !mp_hal_is_interrupted()) { // Use software for small transfers, or if couldn't claim two DMA channels - size_t rx_remaining = in_len; - size_t tx_remaining = out_len; + size_t rx_remaining = in_len / in_stride_in_bytes; + size_t tx_remaining = out_len / out_stride_in_bytes; while (rx_remaining || tx_remaining) { - if (tx_remaining && !pio_sm_is_tx_fifo_full(self->pio, self->state_machine)) { - *tx_destination = *data_out; - data_out++; + while (tx_remaining && !pio_sm_is_tx_fifo_full(self->pio, self->state_machine)) { + 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); + } else if (out_stride_in_bytes == 4) { + *((uint32_t *)tx_destination) = *((uint32_t *)data_out); + } + data_out += out_stride_in_bytes; --tx_remaining; } - if (rx_remaining && !pio_sm_is_rx_fifo_empty(self->pio, self->state_machine)) { - *data_in = (uint8_t) *rx_source; - data_in++; + 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; + } else if (in_stride_in_bytes == 2) { + *((uint16_t *)data_in) = *((uint16_t *)rx_source); + } else if (in_stride_in_bytes == 4) { + *((uint32_t *)data_in) = *((uint32_t *)rx_source); + } + data_in += in_stride_in_bytes; --rx_remaining; } RUN_BACKGROUND_TASKS; @@ -562,24 +711,107 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, } } // Clear the stall bit so we can detect when the state machine is done transmitting. - self->pio->fdebug = PIO_FDEBUG_TXSTALL_BITS; + self->pio->fdebug = stall_mask; } // Wait for the state machine to finish transmitting the data we've queued // up. if (tx) { while (!pio_sm_is_tx_fifo_empty(self->pio, self->state_machine) || - (self->pio->fdebug & PIO_FDEBUG_TXSTALL_BITS) == 0) { + (self->wait_for_txstall && (self->pio->fdebug & stall_mask) == 0)) { RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + break; + } } } return true; } -// Writes out the given data. -bool common_hal_rp2pio_statemachine_write(rp2pio_statemachine_obj_t *self, - const uint8_t *data, size_t len) { +// TODO: Provide a way around these checks in case someone wants to use the FIFO +// with manually run code. + +bool common_hal_rp2pio_statemachine_write(rp2pio_statemachine_obj_t *self, const uint8_t *data, size_t len, uint8_t stride_in_bytes) { if (!self->out) { mp_raise_RuntimeError(translate("No out in program")); } - return _transfer(self, data, len, NULL, 0); + return _transfer(self, data, len, stride_in_bytes, NULL, 0, 0); +} + +bool common_hal_rp2pio_statemachine_readinto(rp2pio_statemachine_obj_t *self, uint8_t *data, size_t len, uint8_t stride_in_bytes) { + if (!self->in) { + mp_raise_RuntimeError(translate("No in in program")); + } + return _transfer(self, NULL, 0, 0, data, len, 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) { + 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) { + uint32_t stall_mask = 1 << (PIO_FDEBUG_RXSTALL_LSB + self->state_machine); + return (self->pio->fdebug & stall_mask) != 0; +} + +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]; + } + self->pio->fdebug = stall_mask; +} + +size_t common_hal_rp2pio_statemachine_get_in_waiting(rp2pio_statemachine_obj_t *self) { + uint8_t level = pio_sm_get_rx_fifo_level(self->pio, self->state_machine); + return level; +} + +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; + + common_hal_mcu_disable_interrupts(); + uint32_t inte = self->pio->inte0; + inte &= ~((PIO_IRQ0_INTF_SM0_RXNEMPTY_BITS | PIO_IRQ0_INTF_SM0_TXNFULL_BITS | PIO_IRQ0_INTF_SM0_BITS) << sm); + inte |= (mask << sm); + self->pio->inte0 = inte; + _interrupt_arg[pio_index][sm] = arg; + _interrupt_handler[pio_index][sm] = handler; + irq_set_exclusive_handler(PIO0_IRQ_0 + 2 * pio_index, rp2pio_statemachine_interrupt_handler); + irq_set_enabled(PIO0_IRQ_0 + 2 * pio_index, true); + common_hal_mcu_enable_interrupts(); +} + +STATIC void rp2pio_statemachine_interrupt_handler(void) { + for (size_t pio_index = 0; pio_index < NUM_PIOS; pio_index++) { + PIO pio = pio_instances[pio_index]; + for (size_t sm = 0; sm < NUM_PIO_STATE_MACHINES; sm++) { + if (!_interrupt_handler[pio_index][sm]) { + continue; + } + uint32_t intf = (PIO_IRQ0_INTF_SM0_RXNEMPTY_BITS | PIO_IRQ0_INTF_SM0_TXNFULL_BITS | PIO_IRQ0_INTF_SM0_BITS) << sm; + if (pio->ints0 & intf) { + _interrupt_handler[pio_index][sm](_interrupt_arg[pio_index][sm]); + } + } + } +} + +uint8_t rp2pio_statemachine_program_offset(rp2pio_statemachine_obj_t *self) { + uint8_t pio_index = pio_get_index(self->pio); + uint8_t sm = self->state_machine; + return _current_program_offset[pio_index][sm]; +} + +void rp2pio_statemachine_set_wrap(rp2pio_statemachine_obj_t *self, uint wrap_target, uint wrap) { + uint8_t sm = self->state_machine; + uint8_t offset = rp2pio_statemachine_program_offset(self); + + pio_sm_set_wrap(self->pio, sm, offset+wrap_target, offset+wrap); } diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h index 6b70b6b5b5b2e..2503aace8d7f8 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h @@ -29,6 +29,7 @@ #include "py/obj.h" +#include "common-hal/microcontroller/Pin.h" #include "src/rp2_common/hardware_pio/include/hardware/pio.h" typedef struct { @@ -36,31 +37,46 @@ typedef struct { uint32_t pins; // Bitmask of what pins this state machine uses. int state_machine; PIO pio; + const uint16_t *init; + size_t init_len; + uint32_t initial_pin_state; + uint32_t initial_pin_direction; + uint32_t pull_pin_up; + uint32_t pull_pin_down; bool in; bool out; + bool wait_for_txstall; uint tx_dreq; uint rx_dreq; bool out_shift_right; bool in_shift_right; uint32_t actual_frequency; + pio_sm_config sm_config; + uint8_t offset; } rp2pio_statemachine_obj_t; 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 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 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, + 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, + bool wait_for_txstall, bool auto_push, uint8_t push_threshold, bool in_shift_right, bool claim_pins); +uint8_t rp2pio_statemachine_program_offset(rp2pio_statemachine_obj_t *self); +void rp2pio_statemachine_set_wrap(rp2pio_statemachine_obj_t *self, uint wrap_target, uint wrap); + void rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self, bool leave_pins); extern const mp_obj_type_t rp2pio_statemachine_type; diff --git a/ports/raspberrypi/common-hal/rp2pio/__init__.c b/ports/raspberrypi/common-hal/rp2pio/__init__.c index 21699dfa36958..ae4cb93d182bf 100644 --- a/ports/raspberrypi/common-hal/rp2pio/__init__.c +++ b/ports/raspberrypi/common-hal/rp2pio/__init__.c @@ -1 +1,43 @@ -// Nothing yet. +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "bindings/rp2pio/__init__.h" + +bool common_hal_rp2pio_pins_are_sequential(size_t len, mp_obj_t *items) { + if (len == 0) { + return true; + } + mcu_pin_obj_t *last_pin = validate_obj_is_pin(items[0]); + for (int i = 1; i < len; i++) { + mcu_pin_obj_t *pin = validate_obj_is_pin(items[i]); + if (pin->number != last_pin->number + 1) { + return false; + } + } + return true; +} diff --git a/ports/raspberrypi/common-hal/rtc/RTC.c b/ports/raspberrypi/common-hal/rtc/RTC.c index 89c23fc190e6b..8647fc246cef2 100644 --- a/ports/raspberrypi/common-hal/rtc/RTC.c +++ b/ports/raspberrypi/common-hal/rtc/RTC.c @@ -29,9 +29,23 @@ #include "py/runtime.h" #include "src/rp2_common/hardware_rtc/include/hardware/rtc.h" +#include "src/rp2_common/hardware_clocks/include/hardware/clocks.h" 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 + }; + + // Start the RTC rtc_init(); + rtc_set_datetime(&t); + } void common_hal_rtc_get_time(timeutils_struct_time_t *tm) { @@ -39,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; } } @@ -57,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 6be38f216ac16..f827651781f10 --- a/ports/raspberrypi/common-hal/supervisor/Runtime.c +++ b/ports/raspberrypi/common-hal/supervisor/Runtime.c @@ -28,10 +28,10 @@ #include "shared-bindings/supervisor/Runtime.h" #include "supervisor/serial.h" -bool common_hal_get_serial_connected(void) { - return (bool) serial_connected(); +bool common_hal_supervisor_runtime_get_serial_connected(void) { + return (bool)serial_connected(); } -bool common_hal_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); +bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { + return (bool)serial_bytes_available(); } diff --git a/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.h b/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.h index ec1e2f6592829..ce34f0b8ab1e3 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 c65a73a428fcc..e6eee2049511d 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/gen_stage2.py b/ports/raspberrypi/gen_stage2.py new file mode 100644 index 0000000000000..4a67905183e89 --- /dev/null +++ b/ports/raspberrypi/gen_stage2.py @@ -0,0 +1,82 @@ +import sys +import cascadetoml +import pathlib +import typer +from jinja2 import Template + + +def main(input_template: pathlib.Path, output_path: pathlib.Path, skus: str = typer.Argument("")): + if "," in skus: + skus = skus.split(",") + else: + skus = [skus] + skus = ['sku="{}"'.format(f.strip()) for f in skus] + flashes = cascadetoml.filter_toml(pathlib.Path("../../data/nvm.toml"), skus) + + if len(skus) == 0: + print("Set EXTERNAL_FLASH_DEVICES in mpconfigboard.mk with all possible flash skus") + raise typer.Exit(code=1) + + def all_have(nvms, key): + for nvm in nvms: + if not nvm.get(key, False): + return False + return True + + def all_match(nvms, key, default=None): + shared_value = nvms[0].get(key, default) + for nvm in nvms: + this_value = nvm.get(key, default) + if this_value != shared_value: + print( + "{}.{} = {} does not match {}".format( + nvm["sku"], key, this_value, shared_value + ) + ) + return None + return shared_value + + quad_enable_status_byte = all_match(flashes["nvm"], "quad_enable_status_byte", None) + quad_enable_bit_mask = all_match(flashes["nvm"], "quad_enable_bit_mask") + continuous_status_write = all_have(flashes["nvm"], "01_continuous_status_write") + split_status_write = all_have(flashes["nvm"], "write_status_register_split") + e7_quad_word_read = all_have(flashes["nvm"], "e7_quad_word_read") + + quad_ok = quad_enable_status_byte is not None and quad_enable_bit_mask is not None + + max_clock_speed_mhz = min((x.get("max_clock_speed_mhz", 1000) for x in flashes["nvm"])) + + # Check that we have a consistent way to set quad enable. + if continuous_status_write is None and split_status_write is None: + print("quad not ok", continuous_status_write, split_status_write) + quad_ok = False + + clock_divider = 4 + + read_command = 0x03 + wait_cycles = 0 + if quad_ok: + if e7_quad_word_read: + read_command = 0xE7 + wait_cycles = 2 + else: + read_command = 0xEB + wait_cycles = 4 + + flash_settings = { + "quad_ok": quad_ok, + "quad_enable_status_byte": quad_enable_status_byte, + "quad_enable_bit_mask": quad_enable_bit_mask, + "split_status_write": split_status_write, + "clock_divider": clock_divider, + "read_command": read_command, + "wait_cycles": wait_cycles, + } + + template = Template(input_template.read_text()) + + output_path.write_text(template.render(flash_settings)) + + +if __name__ == "__main__": + typer.run(main) diff --git a/ports/raspberrypi/link.ld b/ports/raspberrypi/link.ld index d642fd680711f..62b1bd04b68b1 100644 --- a/ports/raspberrypi/link.ld +++ b/ports/raspberrypi/link.ld @@ -23,7 +23,7 @@ MEMORY { - FLASH_FIRMWARE (rx) : ORIGIN = 0x10000000, LENGTH = 1024k + FLASH_FIRMWARE (rx) : ORIGIN = 0x10000000, LENGTH = 1020k RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 256k SCRATCH_X (rwx) : ORIGIN = 0x20040000, LENGTH = 4k SCRATCH_Y (rwx) : ORIGIN = 0x20041000, LENGTH = 4k @@ -59,12 +59,11 @@ SECTIONS */ .text : { - __reset_start = .; - KEEP (*(.reset)) - . = ALIGN(256); - __reset_end = .; - ASSERT(__reset_end - __reset_start == 256, "ERROR: reset section should only be 256 bytes"); + __logical_binary_start = .; KEEP (*(.vectors)) + KEEP (*(.binary_info_header)) + __binary_info_header_end = .; + KEEP (*(.reset)) /* TODO revisit this now memset/memcpy/float in ROM */ /* bit of a hack right now to exclude all floating point and time critical (e.g. memset, memcpy) code from * FLASH ... we will include any thing excluded here in .data below by default */ @@ -175,6 +174,40 @@ SECTIONS __data_end__ = .; } > RAM AT> FLASH_FIRMWARE + .itcm : + { + . = ALIGN(4); + *(.itcm.*) + + . = ALIGN(4); + } > RAM AT> FLASH_FIRMWARE + _ld_itcm_destination = ADDR(.itcm); + _ld_itcm_flash_copy = LOADADDR(.itcm); + _ld_itcm_size = SIZEOF(.itcm); + + .dtcm_data : + { + . = ALIGN(4); + + *(.dtcm_data.*) + + . = ALIGN(4); + } > RAM AT> FLASH_FIRMWARE + _ld_dtcm_data_destination = ADDR(.dtcm_data); + _ld_dtcm_data_flash_copy = LOADADDR(.dtcm_data); + _ld_dtcm_data_size = SIZEOF(.dtcm_data); + + .dtcm_bss : + { + . = ALIGN(4); + + *(.dtcm_bss.*) + + . = ALIGN(4); + } > RAM AT> RAM + _ld_dtcm_bss_start = ADDR(.dtcm_bss); + _ld_dtcm_bss_size = SIZEOF(.dtcm_bss); + .uninitialized_data (COPY): { . = ALIGN(4); *(.uninitialized_data*) @@ -246,5 +279,7 @@ SECTIONS /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed") + + ASSERT( __binary_info_header_end - __logical_binary_start <= 256, "Binary info must be in first 256 bytes of the binary") /* todo assert on extra code */ } diff --git a/ports/raspberrypi/mpconfigport.h b/ports/raspberrypi/mpconfigport.h index 77d1ff08058cd..0259ffd02398d 100644 --- a/ports/raspberrypi/mpconfigport.h +++ b/ports/raspberrypi/mpconfigport.h @@ -27,20 +27,25 @@ #ifndef __INCLUDED_MPCONFIGPORT_H #define __INCLUDED_MPCONFIGPORT_H -#define MICROPY_PY_SYS_PLATFORM "RP2040" +#include "src/rp2040/hardware_regs/include/hardware/platform_defs.h" -#define CIRCUITPY_INTERNAL_NVM_SIZE 0 +#define MICROPY_PY_SYS_PLATFORM "RP2040" -#define CIRCUITPY_DEFAULT_STACK_SIZE (24*1024) +#define CIRCUITPY_INTERNAL_NVM_SIZE (4 * 1024) +#define CIRCUITPY_INTERNAL_NVM_START_ADDR (0x100FF000) + +#define CIRCUITPY_DEFAULT_STACK_SIZE (24 * 1024) #define MICROPY_USE_INTERNAL_PRINTF (1) -#define CIRCUITPY_PROCESSOR_COUNT (2) +#define CIRCUITPY_PROCESSOR_COUNT (2) // This also includes mpconfigboard.h. #include "py/circuitpy_mpconfig.h" #define MICROPY_PORT_ROOT_POINTERS \ + mp_obj_t counting[NUM_PWM_SLICES]; \ + mp_obj_t playing_audio[NUM_DMA_CHANNELS]; \ CIRCUITPY_COMMON_ROOT_POINTERS; #endif // __INCLUDED_MPCONFIGPORT_H diff --git a/ports/raspberrypi/mpconfigport.mk b/ports/raspberrypi/mpconfigport.mk index d0a21a7b41d27..ed0eeba8f0dea 100644 --- a/ports/raspberrypi/mpconfigport.mk +++ b/ports/raspberrypi/mpconfigport.mk @@ -17,31 +17,40 @@ endif # All raspberrypi ports have longints. LONGINT_IMPL = MPZ -ifndef CIRCUITPY_RP2PIO -CIRCUITPY_RP2PIO = 1 -else -CIRCUITPY_NEOPIXEL_WRITE = 0 -endif - -CIRCUITPY_FULL_BUILD = 1 -CIRCUITPY_PWMIO = 1 +CIRCUITPY_RP2PIO ?= 1 +CIRCUITPY_NEOPIXEL_WRITE ?= $(CIRCUITPY_RP2PIO) +CIRCUITPY_FRAMEBUFFERIO ?= 1 +CIRCUITPY_FULL_BUILD ?= 1 +CIRCUITPY_AUDIOMP3 ?= 1 +CIRCUITPY_BITOPS ?= 1 +CIRCUITPY_IMAGECAPTURE ?= 1 +CIRCUITPY_PWMIO ?= 1 +CIRCUITPY_RGBMATRIX ?= 1 +CIRCUITPY_ROTARYIO ?= 1 +CIRCUITPY_ROTARYIO_SOFTENCODER = 1 # Things that need to be implemented. -CIRCUITPY_AUDIOBUSIO = 0 # Use PIO interally for I2S -CIRCUITPY_AUDIOMP3 = 0 -CIRCUITPY_COUNTIO = 0 # Use PWM interally -CIRCUITPY_FREQUENCYIO = 0 # Use PWM interally +# Use PWM interally +CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_I2CPERIPHERAL = 0 -CIRCUITPY_NVM = 0 -CIRCUITPY_PULSEIO = 0 # Use PIO interally -CIRCUITPY_ROTARYIO = 0 # Use PIO interally -CIRCUITPY_WATCHDOG = 1 +CIRCUITPY_NVM = 1 +# Use PIO interally +CIRCUITPY_PULSEIO ?= 1 +CIRCUITPY_WATCHDOG ?= 1 -# Things that are unsupported by the hardware. +# Audio via PWM CIRCUITPY_AUDIOIO = 0 +CIRCUITPY_AUDIOBUSIO ?= 1 +CIRCUITPY_AUDIOCORE ?= 1 +CIRCUITPY_AUDIOPWMIO ?= 1 + +CIRCUITPY_AUDIOMIXER = 1 INTERNAL_LIBM = 1 -USB_SERIAL_NUMBER_LENGTH = 32 +USB_SERIAL_NUMBER_LENGTH = 16 +# Number of USB endpoint pairs. USB_NUM_EP = 8 + +INTERNAL_FLASH_FILESYSTEM = 1 diff --git a/ports/raspberrypi/mphalport.h b/ports/raspberrypi/mphalport.h index 8d2d7d51a2fb8..6d47534388679 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 a2a7b85bd337b..1b5fe91cac769 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/sdk b/ports/raspberrypi/sdk index 26653ea81e340..7a6660134ac62 160000 --- a/ports/raspberrypi/sdk +++ b/ports/raspberrypi/sdk @@ -1 +1 @@ -Subproject commit 26653ea81e340cacee55025d110c3e014a252a87 +Subproject commit 7a6660134ac6242e3223fe1c78b248caf6b2cbf4 diff --git a/ports/raspberrypi/stage2.c.jinja b/ports/raspberrypi/stage2.c.jinja new file mode 100644 index 0000000000000..13de7bff9fdb9 --- /dev/null +++ b/ports/raspberrypi/stage2.c.jinja @@ -0,0 +1,196 @@ +#include "sdk/src/rp2040/hardware_structs/include/hardware/structs/ssi.h" +#include "sdk/src/rp2040/hardware_structs/include/hardware/structs/pads_qspi.h" +#include "sdk/src/rp2040/hardware_regs/include/hardware/regs/addressmap.h" +#include "sdk/src/rp2040/hardware_regs/include/hardware/regs/m0plus.h" + +// "Mode bits" are 8 special bits sent immediately after +// the address bits in a "Read Data Fast Quad I/O" command sequence. +// On W25Q080, the four LSBs are don't care, and if MSBs == 0xa, the +// next read does not require the 0xeb instruction prefix. +#define MODE_CONTINUOUS_READ 0xa0 + +// Define interface width: single/dual/quad IO +{% if quad_ok %} +#define FRAME_FORMAT SSI_CTRLR0_SPI_FRF_VALUE_QUAD +#define TRANSACTION_TYPE SSI_SPI_CTRLR0_TRANS_TYPE_VALUE_2C2A +// Note that the INST_L field is used to select what XIP data gets pushed into +// the TX FIFO: +// INST_L_0_BITS {ADDR[23:0],XIP_CMD[7:0]} Load "mode bits" into XIP_CMD +// Anything else {XIP_CMD[7:0],ADDR[23:0]} Load SPI command into XIP_CMD +#define INSTRUCTION_LENGTH SSI_SPI_CTRLR0_INST_L_VALUE_NONE +#define READ_INSTRUCTION MODE_CONTINUOUS_READ +#define ADDR_L 8 // 6 for address, 2 for mode +{% else %} +#define FRAME_FORMAT SSI_CTRLR0_SPI_FRF_VALUE_STD +#define TRANSACTION_TYPE SSI_SPI_CTRLR0_TRANS_TYPE_VALUE_1C1A +#define INSTRUCTION_LENGTH SSI_SPI_CTRLR0_INST_L_VALUE_8B +#define READ_INSTRUCTION (0x{{ '%02x' % read_command }}) +#define ADDR_L 6 // * 4 = 24 +{% endif %} + +#define CMD_READ_STATUS1 0x05 +#define CMD_READ_STATUS2 0x35 +#define CMD_WRITE_ENABLE 0x06 +#define CMD_WRITE_STATUS1 0x01 +#define CMD_WRITE_STATUS2 0x31 + +#define SREG_DATA 0x02 + +static uint32_t wait_and_read(uint8_t); +static uint8_t read_flash_sreg(uint8_t status_command); + +// This function is use by the bootloader to enable the XIP flash. It is also +// used by the SDK to reinit XIP after doing non-read flash interactions such as +// writing or erasing. This code must compile down to position independent +// assembly because we don't know where in RAM it'll be when run. + +// This must be the first defined function so that it is placed at the start of +// memory where the bootloader jumps to! +void __attribute__((section(".entry._stage2_boot"), used)) _stage2_boot(void) { + uint32_t lr; + asm ("MOV %0, LR\n" : "=r" (lr) ); + + // Set aggressive pad configuration for QSPI + // - SCLK 8mA drive, no slew limiting + // - SDx disable input Schmitt to reduce delay + + // SCLK + pads_qspi_hw->io[0] = PADS_QSPI_GPIO_QSPI_SCLK_DRIVE_VALUE_8MA << PADS_QSPI_GPIO_QSPI_SCLK_DRIVE_LSB | + PADS_QSPI_GPIO_QSPI_SCLK_SLEWFAST_BITS; + + // Data lines + uint32_t data_settings = pads_qspi_hw->io[1]; + data_settings &= ~PADS_QSPI_GPIO_QSPI_SCLK_SCHMITT_BITS; + pads_qspi_hw->io[2] = data_settings; + {% if quad_ok %} + pads_qspi_hw->io[1] = data_settings; + pads_qspi_hw->io[3] = data_settings; + pads_qspi_hw->io[4] = data_settings; + {% endif %} + + // Disable the SSI so we can change the settings. + ssi_hw->ssienr = 0; + + // QSPI config + ssi_hw->baudr = {{ clock_divider }}; // 125 mhz / clock divider + + // Set 1-cycle sample delay. If PICO_FLASH_SPI_CLKDIV == 2 then this means, + // if the flash launches data on SCLK posedge, we capture it at the time that + // the next SCLK posedge is launched. This is shortly before that posedge + // arrives at the flash, so data hold time should be ok. For + // PICO_FLASH_SPI_CLKDIV > 2 this pretty much has no effect. + ssi_hw->rx_sample_dly = 1; + + // Set a temporary mode for doing simple commands. + ssi_hw->ctrlr0 = (7 << SSI_CTRLR0_DFS_32_LSB) | // 8 bits per data frame + (SSI_CTRLR0_TMOD_VALUE_TX_AND_RX << SSI_CTRLR0_TMOD_LSB); + + ssi_hw->ssienr = 0x1; + + {% if quad_ok %} + // Program status register. + // Enable SSI and select slave 0 + {% if quad_enable_status_byte == 1 %} + uint8_t result = read_flash_sreg(CMD_READ_STATUS1); + {% elif quad_enable_status_byte == 2 %} + uint8_t result = read_flash_sreg(CMD_READ_STATUS2); + {% endif %} + if (result != {{ quad_enable_bit_mask }}) { + ssi_hw->dr0 = (uint8_t) CMD_WRITE_ENABLE; + wait_and_read(1); + + {% if split_status_write %} + {% if quad_enable_status_byte == 1 %} + ssi_hw->dr0 = (uint8_t) CMD_WRITE_STATUS1; + {% elif quad_enable_status_byte == 2 %} + ssi_hw->dr0 = (uint8_t) CMD_WRITE_STATUS2; + {% endif %} + ssi_hw->dr0 = {{ quad_enable_bit_mask }}; + wait_and_read(2); + {% else %} + ssi_hw->dr0 = (uint8_t) CMD_WRITE_STATUS1; + {% if quad_enable_status_byte == 2 %} + ssi_hw->dr0 = 0x0; + {% endif %} + ssi_hw->dr0 = {{ quad_enable_bit_mask }}; + wait_and_read({{ quad_enable_status_byte + 1 }}); + {% endif %} + // Wait for the write to complete. + while ((read_flash_sreg(CMD_READ_STATUS1) & 0x1) != 0) {} + } + {% endif %} + + // Disable SSI again so that it can be reconfigured + ssi_hw->ssienr = 0; + + // Do a single read to get us in continuous mode. + + // Final SSI ctrlr0 settings. We only change the SPI specific settings later. + ssi_hw->ctrlr0 = (FRAME_FORMAT << SSI_CTRLR0_SPI_FRF_LSB) | // Quad I/O mode + (31 << SSI_CTRLR0_DFS_32_LSB) | // 32 data bits + (SSI_CTRLR0_TMOD_VALUE_EEPROM_READ << SSI_CTRLR0_TMOD_LSB); // Send INST/ADDR, Receive Data + + ssi_hw->ctrlr1 = 0; // Single 32b read + + {% if quad_ok %} + ssi_hw->spi_ctrlr0 = (ADDR_L << SSI_SPI_CTRLR0_ADDR_L_LSB) | // Address + mode bits + // Hi-Z dummy clocks following address + mode + ({{ wait_cycles }} << SSI_SPI_CTRLR0_WAIT_CYCLES_LSB) | + // 8-bit instruction + (SSI_SPI_CTRLR0_INST_L_VALUE_8B << SSI_SPI_CTRLR0_INST_L_LSB) | + // Send Command in serial mode then address in Quad I/O mode + (SSI_SPI_CTRLR0_TRANS_TYPE_VALUE_1C2A << SSI_SPI_CTRLR0_TRANS_TYPE_LSB); + + // Re-enable the SSI + ssi_hw->ssienr = 1; + + // Do a single read to get us in continuous mode. + ssi_hw->dr0 = 0x{{ '%02x' % read_command }}; + ssi_hw->dr0 = MODE_CONTINUOUS_READ; + wait_and_read(2); + + // Disable the SSI to switch to no-command mode (because we're setup for continuous.) + ssi_hw->ssienr = 0; + {% endif %} + + // Final SPI ctrlr0 settings. + ssi_hw->spi_ctrlr0 = (READ_INSTRUCTION << SSI_SPI_CTRLR0_XIP_CMD_LSB) | // Mode bits to keep flash in continuous read mode + (ADDR_L << SSI_SPI_CTRLR0_ADDR_L_LSB) | // Total number of address + mode bits + ({{ wait_cycles }} << SSI_SPI_CTRLR0_WAIT_CYCLES_LSB) | // Hi-Z dummy clocks following address + mode + (INSTRUCTION_LENGTH << SSI_SPI_CTRLR0_INST_L_LSB) | // Do not send a command, instead send XIP_CMD as mode bits after address + (TRANSACTION_TYPE << SSI_SPI_CTRLR0_TRANS_TYPE_LSB); // Send Address in Quad I/O mode (and Command but that is zero bits long) + + // Re-enable the SSI + ssi_hw->ssienr = 1; + + // If lr is 0, then we came from the bootloader. + if (lr == 0) { + uint32_t* vector_table = (uint32_t*) (XIP_BASE + 0x100); + // Switch the vector table to immediately after the stage 2 area. + *((uint32_t *) (PPB_BASE + M0PLUS_VTOR_OFFSET)) = (uint32_t) vector_table; + // Set the top of the stack according to the vector table. + asm volatile ("MSR msp, %0" : : "r" (vector_table[0]) : ); + // The reset handler is the second entry in the vector table + asm volatile ("bx %0" : : "r" (vector_table[1]) : ); + // Doesn't return. It jumps to the reset handler instead. + } + // Otherwise we return. +} + +static uint32_t wait_and_read(uint8_t count) { + while ((ssi_hw->sr & SSI_SR_TFE_BITS) == 0) {} + while ((ssi_hw->sr & SSI_SR_BUSY_BITS) != 0) {} + uint32_t result = 0; + while (count > 0) { + result = ssi_hw->dr0; + count--; + } + return result; +} + +static uint8_t read_flash_sreg(uint8_t status_command) { + ssi_hw->dr0 = status_command; + ssi_hw->dr0 = status_command; + + return wait_and_read(2); +} diff --git a/ports/raspberrypi/supervisor/internal_flash.c b/ports/raspberrypi/supervisor/internal_flash.c index d333830de985e..51068e184a00f 100644 --- a/ports/raspberrypi/supervisor/internal_flash.c +++ b/ports/raspberrypi/supervisor/internal_flash.c @@ -44,27 +44,39 @@ #include "src/rp2_common/hardware_flash/include/hardware/flash.h" #include "src/common/pico_binary_info/include/pico/binary_info.h" -#define RESERVED_FLASH 1 * 1024 * 1024 - -// TODO: Parameterize flash size based on the configured flash. -#define TOTAL_FLASH_SIZE 2 * 1024 * 1024 +#define RESERVED_FLASH (1 * 1024 * 1024) // TODO: Split the caching out of supervisor/shared/external_flash so we can use it. #define SECTOR_SIZE 4096 #define NO_CACHE 0xffffffff STATIC uint8_t _cache[SECTOR_SIZE]; STATIC uint32_t _cache_lba = NO_CACHE; +STATIC uint32_t _flash_size = 0; void supervisor_flash_init(void) { bi_decl_if_func_used(bi_block_device( BINARY_INFO_MAKE_TAG('C', 'P'), "CircuitPython", RESERVED_FLASH, - TOTAL_FLASH_SIZE - RESERVED_FLASH, + (1 * 1024 * 1024), // This is a minimum. We can't set it dynamically. NULL, BINARY_INFO_BLOCK_DEV_FLAG_READ | BINARY_INFO_BLOCK_DEV_FLAG_WRITE | BINARY_INFO_BLOCK_DEV_FLAG_PT_UNKNOWN)); + + // Read the RDID register to get the flash capacity. + uint8_t cmd[] = {0x9f, 0, 0, 0}; + uint8_t data[4]; + flash_do_cmd(cmd, data, 4); + uint8_t power_of_two = 21; + // Flash must be at least 2MB (1 << 21) because we use the first 1MB for the + // CircuitPython core. We validate the range because Adesto Tech flash chips + // don't return the correct value. So, we default to 2MB which will work for + // larger chips, it just won't use all of the space. + if (data[3] >= 21 && data[3] < 30) { + power_of_two = data[3]; + } + _flash_size = 1 << power_of_two; } uint32_t supervisor_flash_get_block_size(void) { @@ -72,7 +84,7 @@ uint32_t supervisor_flash_get_block_size(void) { } uint32_t supervisor_flash_get_block_count(void) { - return (TOTAL_FLASH_SIZE - RESERVED_FLASH) / FILESYSTEM_BLOCK_SIZE; + return (_flash_size - RESERVED_FLASH) / FILESYSTEM_BLOCK_SIZE; } void port_internal_flash_flush(void) { @@ -88,8 +100,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; } @@ -103,18 +115,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 b14f5173d6bc0..9b3e140a855ea 100644 --- a/ports/raspberrypi/supervisor/port.c +++ b/ports/raspberrypi/supervisor/port.c @@ -32,12 +32,16 @@ #include "bindings/rp2pio/StateMachine.h" #include "genhdr/mpversion.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" #include "shared-bindings/busio/I2C.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/rtc/__init__.h" #include "shared-bindings/pwmio/PWMOut.h" +#include "common-hal/rtc/RTC.h" +#include "common-hal/busio/UART.h" + #include "supervisor/shared/safe_mode.h" #include "supervisor/shared/stack.h" #include "supervisor/shared/tick.h" @@ -52,6 +56,8 @@ #include "tusb.h" +#include "pico/bootrom.h" +#include "hardware/watchdog.h" extern volatile bool mp_msc_enabled; @@ -68,13 +74,48 @@ STATIC void _binary_info(void) { // TODO: Add build attribute for debug builds. Needs newer CircuitPython with CIRCUITPY_DEBUG. } +extern uint32_t _ld_dtcm_bss_start; +extern uint32_t _ld_dtcm_bss_size; +extern uint32_t _ld_dtcm_data_destination; +extern uint32_t _ld_dtcm_data_size; +extern uint32_t _ld_dtcm_data_flash_copy; +extern uint32_t _ld_itcm_destination; +extern uint32_t _ld_itcm_size; +extern uint32_t _ld_itcm_flash_copy; + safe_mode_t port_init(void) { _binary_info(); // Set brown out. + // Copy all of the "tightly coupled memory" code and data to run from RAM. + // This lets us use the 16k cache for dynamically used data and code. + // We must do this before we try and call any of its code or load the data. + for (uint32_t i = 0; i < ((size_t)&_ld_itcm_size) / 4; i++) { + (&_ld_itcm_destination)[i] = (&_ld_itcm_flash_copy)[i]; + // Now zero it out to evict the line from the XIP cache. Without this, + // it'll stay in the XIP cache anyway. + (&_ld_itcm_flash_copy)[i] = 0x0; + } + + // Copy all of the data to run from DTCM. + 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]; + // Now zero it out to evict the line from the XIP cache. Without this, + // it'll stay in the XIP cache anyway. + (&_ld_dtcm_data_flash_copy)[i] = 0x0; + } + + // Clear DTCM bss. + for (uint32_t i = 0; i < ((size_t)&_ld_dtcm_bss_size) / 4; i++) { + (&_ld_dtcm_bss_start)[i] = 0; + } + // Reset everything into a known state before board_init. reset_port(); + // Initialize RTC + common_hal_rtc_init(); + // For the tick. hardware_alarm_claim(0); hardware_alarm_set_callback(0, _tick_callback); @@ -92,6 +133,7 @@ void reset_port(void) { #if CIRCUITPY_BUSIO reset_i2c(); reset_spi(); + reset_uart(); #endif #if CIRCUITPY_PWMIO @@ -106,17 +148,29 @@ void reset_port(void) { rtc_reset(); #endif + #if CIRCUITPY_AUDIOPWMIO + audiopwmout_reset(); + #endif + #if CIRCUITPY_AUDIOCORE + audio_dma_reset(); + #endif + reset_all_pins(); } void reset_to_bootloader(void) { - // reset(); - while (true) {} + reset_usb_boot(0, 0); + while (true) { + } } void reset_cpu(void) { - // reset(); - while (true) {} + watchdog_reboot(0, SRAM_END, 0); + watchdog_start_tick(12); + + while (true) { + __wfi(); + } } bool port_has_fixed_stack(void) { @@ -151,7 +205,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; } @@ -189,16 +243,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/raspberrypi/supervisor/usb.c b/ports/raspberrypi/supervisor/usb.c index 1d2425aed2488..799ed06953ac8 100644 --- a/ports/raspberrypi/supervisor/usb.c +++ b/ports/raspberrypi/supervisor/usb.c @@ -31,23 +31,17 @@ #include "src/rp2_common/pico_platform/include/pico/platform.h" #include "src/rp2040/hardware_regs/include/hardware/regs/intctrl.h" -static background_callback_t usb_callback; -static void usb_background_do(void* unused) { - usb_background(); -} - -static void queue_background(void) { - background_callback_add(&usb_callback, usb_background_do, NULL); -} - void init_usb_hardware(void) { } void post_usb_init(void) { + irq_set_enabled(USBCTRL_IRQ, false); + irq_handler_t usb_handler = irq_get_exclusive_handler(USBCTRL_IRQ); if (usb_handler) { irq_remove_handler(USBCTRL_IRQ, usb_handler); - irq_add_shared_handler(USBCTRL_IRQ, usb_handler, PICO_DEFAULT_IRQ_PRIORITY); } - irq_add_shared_handler(USBCTRL_IRQ, queue_background, PICO_LOWEST_IRQ_PRIORITY); + irq_set_exclusive_handler(USBCTRL_IRQ, usb_irq_handler); + + irq_set_enabled(USBCTRL_IRQ, true); } diff --git a/ports/stm/Makefile b/ports/stm/Makefile index e09fe736cc4ac..49548b0db3eab 100755 --- a/ports/stm/Makefile +++ b/ports/stm/Makefile @@ -238,7 +238,7 @@ SRC_C += \ lib/utils/sys_stdio_mphal.c \ supervisor/shared/memory.c -ifneq ($(USB),FALSE) +ifneq ($(CIRCUITPY_USB),0) SRC_C += lib/tinyusb/src/portable/st/synopsys/dcd_synopsys.c endif diff --git a/ports/stm/background.c b/ports/stm/background.c index d83a0ccec7c19..dbf5ccee2b2ec 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 fe4ed6ca254c9..9a3f93864e0d2 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_pico/mpconfigboard.mk b/ports/stm/boards/espruino_pico/mpconfigboard.mk index 81c3772e72103..91481602861b0 100644 --- a/ports/stm/boards/espruino_pico/mpconfigboard.mk +++ b/ports/stm/boards/espruino_pico/mpconfigboard.mk @@ -20,6 +20,10 @@ LD_FILE = boards/STM32F401xd_fs.ld # lto for this port, and if other stuff hasn't been added in the # meantime CIRCUITPY_ULAB = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_AUDIOPWMIO = 0 CIRCUITPY_BUSDEVICE = 0 +CIRCUITPY_BITMAPTOOLS = 0 +CIRCUITPY_FRAMEBUFFERIO = 0 SUPEROPT_GC = 0 diff --git a/ports/stm/boards/espruino_wifi/board.c b/ports/stm/boards/espruino_wifi/board.c index 78179332815e6..688cfb4ded1bc 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 b7f38f69becda..b857650d6ba05 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/mpconfigboard.mk b/ports/stm/boards/espruino_wifi/mpconfigboard.mk index 9500a5f18583d..a2ceb1ae3843a 100644 --- a/ports/stm/boards/espruino_wifi/mpconfigboard.mk +++ b/ports/stm/boards/espruino_wifi/mpconfigboard.mk @@ -11,3 +11,7 @@ MCU_PACKAGE = UFQFPN48 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F411_fs.ld + +# Too big for the flash +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_AUDIOPWMIO = 0 diff --git a/ports/stm/boards/espruino_wifi/pins.c b/ports/stm/boards/espruino_wifi/pins.c index 8800317d50c8a..2d36ae8b957d3 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 e69be6cf95668..8558edd8cd20f 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/feather_stm32f405_express/mpconfigboard.mk b/ports/stm/boards/feather_stm32f405_express/mpconfigboard.mk index 4d0bd4598d46b..e525ebe1ef525 100644 --- a/ports/stm/boards/feather_stm32f405_express/mpconfigboard.mk +++ b/ports/stm/boards/feather_stm32f405_express/mpconfigboard.mk @@ -4,7 +4,6 @@ USB_PRODUCT = "Feather STM32F405 Express" USB_MANUFACTURER = "Adafruit Industries LLC" SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C MCU_SERIES = F4 @@ -16,3 +15,5 @@ LD_DEFAULT = boards/STM32F405_default.ld # UF2 boot option LD_BOOT = boards/STM32F405_boot.ld UF2_OFFSET = 0x8010000 + +CIRCUITPY_RGBMATRIX ?= 1 diff --git a/ports/stm/boards/meowbit_v121/board.c b/ports/stm/boards/meowbit_v121/board.c index 4a8014a3a1093..7a31c14e7e24b 100644 --- a/ports/stm/boards/meowbit_v121/board.c +++ b/ports/stm/boards/meowbit_v121/board.c @@ -27,50 +27,50 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" #include "shared-bindings/board/__init__.h" -#include "shared-bindings/displayio/FourWire.h" #include "shared-module/displayio/__init__.h" #include "shared-module/displayio/mipi_constants.h" #include "shared-bindings/busio/SPI.h" #include "supervisor/spi_flash_api.h" -displayio_fourwire_obj_t board_display_obj; +audiopwmio_pwmaudioout_obj_t board_buzz_obj; #define DELAY 0x80 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, @@ -113,6 +113,11 @@ void board_init(void) { 60, // native_frames_per_second true, // backlight_on_high false); // SH1107_addressing + + board_buzz_obj.base.type = &audiopwmio_pwmaudioout_type; + common_hal_audiopwmio_pwmaudioout_construct(&board_buzz_obj, + &pin_PB08, NULL, 0x8000); + never_reset_pin_number(pin_PB08.port, pin_PB08.number); } bool board_requests_safe_mode(void) { diff --git a/ports/stm/boards/meowbit_v121/mpconfigboard.h b/ports/stm/boards/meowbit_v121/mpconfigboard.h index be9f2a75fba75..7807437941e56 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/mpconfigboard.mk b/ports/stm/boards/meowbit_v121/mpconfigboard.mk index 86b0cb5ab4241..dc44095a316c3 100644 --- a/ports/stm/boards/meowbit_v121/mpconfigboard.mk +++ b/ports/stm/boards/meowbit_v121/mpconfigboard.mk @@ -4,8 +4,7 @@ USB_PRODUCT = "Meowbit" USB_MANUFACTURER = "Kittenbot" SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = W25Q16JV_IQ +EXTERNAL_FLASH_DEVICES = W25Q16JVxQ # INTERNAL_FLASH_FILESYSTEM = 1 BOOTLOADER_OFFSET = 0x8010000 diff --git a/ports/stm/boards/meowbit_v121/pins.c b/ports/stm/boards/meowbit_v121/pins.c index af896fad87a51..fd988b5919347 100644 --- a/ports/stm/boards/meowbit_v121/pins.c +++ b/ports/stm/boards/meowbit_v121/pins.c @@ -1,8 +1,11 @@ #include "shared-bindings/board/__init__.h" #include "supervisor/spi_flash_api.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" #include "shared-module/displayio/__init__.h" +extern audiopwmio_pwmaudioout_obj_t board_buzz_obj; + STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_PB04) }, { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_PB05) }, @@ -15,7 +18,7 @@ STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_DISP_RST), MP_ROM_PTR(&pin_PB10) }, { MP_ROM_QSTR(MP_QSTR_DISP_BL), MP_ROM_PTR(&pin_PB03) }, - { MP_ROM_QSTR(MP_QSTR_BUZZ), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_BUZZ), MP_ROM_PTR(&board_buzz_obj) }, { MP_ROM_QSTR(MP_QSTR_BTNA), MP_ROM_PTR(&pin_PB09) }, { MP_ROM_QSTR(MP_QSTR_BTNB), MP_ROM_PTR(&pin_PC03) }, { MP_ROM_QSTR(MP_QSTR_RIGHT), MP_ROM_PTR(&pin_PB02) }, @@ -55,7 +58,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 78179332815e6..688cfb4ded1bc 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 e2b54335a5c36..ef8f84ceba439 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 7c6a075e235ae..251ce4bcbaa67 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 78179332815e6..688cfb4ded1bc 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 327651923a0eb..8db104e871efa 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 9ecc38f01f2ad..0373fc4fb6a96 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 78179332815e6..688cfb4ded1bc 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 2ac986701e05f..36c55a26aa7c6 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 78179332815e6..688cfb4ded1bc 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 77ae235ecf2e2..ffeba28f62303 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 7c1ab31e34eb8..0960687d1eff5 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/pyb_nano_v2/mpconfigboard.mk b/ports/stm/boards/pyb_nano_v2/mpconfigboard.mk index 237dba921e136..5824e65a29f4d 100644 --- a/ports/stm/boards/pyb_nano_v2/mpconfigboard.mk +++ b/ports/stm/boards/pyb_nano_v2/mpconfigboard.mk @@ -4,8 +4,7 @@ USB_PRODUCT = "PYB LR Nano V2" USB_MANUFACTURER = "MicroPython Chinese Community" SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 -EXTERNAL_FLASH_DEVICES = W25Q64JV_IQ +EXTERNAL_FLASH_DEVICES = W25Q64JVxQ MCU_SERIES = F4 MCU_VARIANT = STM32F411xE @@ -13,3 +12,7 @@ MCU_PACKAGE = UFQFPN48 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F411_fs.ld + +# Too big for the flash +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_AUDIOPWMIO = 0 diff --git a/ports/stm/boards/pyboard_v11/board.c b/ports/stm/boards/pyboard_v11/board.c index 78179332815e6..688cfb4ded1bc 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 50a90c52b09e9..1ce89a59fc17e 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/pyboard_v11/mpconfigboard.mk b/ports/stm/boards/pyboard_v11/mpconfigboard.mk index 78b96e55fc5a6..4aff25bb0abf8 100644 --- a/ports/stm/boards/pyboard_v11/mpconfigboard.mk +++ b/ports/stm/boards/pyboard_v11/mpconfigboard.mk @@ -11,3 +11,5 @@ MCU_PACKAGE = LQFP64 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F405_fs.ld + +CIRCUITPY_RGBMATRIX ?= 1 diff --git a/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.h b/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.h index 4351339540f0b..400e7bb2c1a76 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/mpconfigboard.mk b/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.mk index 9b45a0fac7f8e..bfb88ab0ea0dd 100644 --- a/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.mk +++ b/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.mk @@ -4,7 +4,6 @@ USB_PRODUCT = "stm32f411ce blackpill" USB_MANUFACTURER = "Unknown" # SPI_FLASH_FILESYSTEM = 1 -# EXTERNAL_FLASH_DEVICE_COUNT = 1 # EXTERNAL_FLASH_DEVICES = xxxxxx #See supervisor/shared/external_flash/devices.h for options # LONGINT_IMPL = MPZ @@ -16,3 +15,7 @@ MCU_PACKAGE = UFQFPN48 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F411_fs.ld + +# Too big for the flash +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_AUDIOPWMIO = 0 diff --git a/ports/stm/boards/stm32f411ce_blackpill/pins.c b/ports/stm/boards/stm32f411ce_blackpill/pins.c index 16946b8bee4e1..7e25ad042b3a2 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 65e224e47a353..a7d56209c4d1d 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/mpconfigboard.mk b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk index 9a95a3539cc42..211a658967d2f 100644 --- a/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk +++ b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk @@ -4,9 +4,8 @@ USB_PRODUCT = "stm32f411ce blackpill with flash" USB_MANUFACTURER = "Unknown" SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 2 #See supervisor/shared/external_flash/devices.h for options -EXTERNAL_FLASH_DEVICES = W25Q64FV,W25Q64JV_IQ +EXTERNAL_FLASH_DEVICES = GD25Q16C,W25Q64FV,W25Q32JVxQ,W25Q64JVxQ LONGINT_IMPL = MPZ INTERNAL_FLASH_FILESYSTEM = 0 @@ -17,3 +16,5 @@ MCU_PACKAGE = UFQFPN48 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F411_nvm_nofs.ld + +CIRCUITPY_SYNTHIO = 0 diff --git a/ports/stm/boards/stm32f411ce_blackpill_with_flash/pins.c b/ports/stm/boards/stm32f411ce_blackpill_with_flash/pins.c index 16946b8bee4e1..7e25ad042b3a2 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 78179332815e6..688cfb4ded1bc 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 0be43f4fb7a81..ec6e548339a1d 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/mpconfigboard.mk b/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.mk index 3cb7162a4add7..3180fbd0845e0 100644 --- a/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.mk +++ b/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.mk @@ -11,3 +11,7 @@ MCU_PACKAGE = LQFP100_f4 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F411_fs.ld + +# Too big for the flash +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_AUDIOPWMIO = 0 diff --git a/ports/stm/boards/stm32f411ve_discovery/pins.c b/ports/stm/boards/stm32f411ve_discovery/pins.c index 673c412d51606..6261513342bd3 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 78179332815e6..688cfb4ded1bc 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 6b9ab64678d10..3ae0761c7a011 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/mpconfigboard.mk b/ports/stm/boards/stm32f412zg_discovery/mpconfigboard.mk index c99eb1a0082ef..b50cdb966f6ee 100644 --- a/ports/stm/boards/stm32f412zg_discovery/mpconfigboard.mk +++ b/ports/stm/boards/stm32f412zg_discovery/mpconfigboard.mk @@ -6,7 +6,6 @@ USB_MANUFACTURER = "STMicroelectronics" INTERNAL_FLASH_FILESYSTEM = 1 # QSPI_FLASH_FILESYSTEM = 1 -# EXTERNAL_FLASH_DEVICE_COUNT = 1 # EXTERNAL_FLASH_DEVICES = N25Q128A # LONGINT_IMPL = MPZ @@ -16,5 +15,3 @@ MCU_PACKAGE = LQFP144 LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F412_fs.ld - -CIRCUITPY_USB_HID = 1 diff --git a/ports/stm/boards/stm32f412zg_discovery/pins.c b/ports/stm/boards/stm32f412zg_discovery/pins.c index ab90b045581b9..84e646ca7f824 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 78179332815e6..688cfb4ded1bc 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 44ee073780d66..410c21ec9af62 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 712932145aca0..ee53fbd784732 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 db2c72727165d..68bf157b63b14 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 769990a98cd20..afcefe0ce31d2 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 a859c8d190956..bd9c1dcb15c99 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 d8c745dbbd32b..39dc727053614 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; - - /* 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 */ - - /* 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); - } - - 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; +void SystemCoreClockUpdate(void) { + uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; + + /* 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 */ + + /* 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); + } + + 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; - - 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; - - /* 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 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 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 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; +void SystemInit_ExtMemCtl(void) { + __IO uint32_t tmp = 0x00; + + 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; + + /* 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 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 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 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); - - 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)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* Delay */ - for (index = 0; index<1000; index++); + /* Enable the FMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - /* 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; - } + FMC_Bank5_6->SDCR[0] = 0x000019E4; + FMC_Bank5_6->SDTR[0] = 0x01115351; - /* MRD register program */ - FMC_Bank5_6->SDCMR = 0x00046014; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { + /* SDRAM initialization sequence */ + /* Clock enable command */ + FMC_Bank5_6->SDCMR = 0x00000011; tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* 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); - -#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); + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* 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; + } + + /* 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; + } + + /* 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); + + #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); } #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; - -#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; - - /* 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 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 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; - - /* 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 */ +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) + /* 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 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 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; + + #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 */ /*-- 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); - - /* 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)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* 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; - } - - /* 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)) - { + /* 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; + + /* SDRAM initialization sequence */ + /* Clock enable command */ + FMC_Bank5_6->SDCMR = 0x00000011; 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 */ - - /* 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(DATA_IN_ExtSRAM) + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* 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; + } + + /* 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; + } + + /* 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 */ + + #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) /*-- 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); - - /* 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 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; + /* 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 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 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; - -#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 ||\ + /* 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 */ + + #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 4aebc3d35721a..450283ae55e1b 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 +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 + /* 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 */ + 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 */ + 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; - - /* 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 */ - - /* 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); - } - - 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; +void SystemCoreClockUpdate(void) { + uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; + + /* 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 */ + + /* 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); + } + + 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 bbb0f821fbe60..8b782e4960b8d 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 */ - - /* 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 +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 */ + 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 */ + SCB->VTOR = FLASH_BANK1_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ + #endif #endif -#endif -#endif /*DUAL_CORE && CORE_CM4*/ + #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; - - - /* 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; +void SystemCoreClockUpdate(void) { + uint32_t pllp, pllsource, pllm, pllfracen, hsivalue, tmp; + uint32_t common_system_clock; + float_t fracn1, pllvco; - 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)); + /* Get SYSCLK source -------------------------------------------------------*/ - if (pllm != 0U) + switch (RCC->CFGR & RCC_CFGR_SWS) { - 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); + 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 (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 78179332815e6..688cfb4ded1bc 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 7d4a8dff32966..9c3c116e51e34 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 78179332815e6..688cfb4ded1bc 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 fb5f389a370a6..34a5795ff172c 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/boards/thunderpack_v12/mpconfigboard.mk b/ports/stm/boards/thunderpack_v12/mpconfigboard.mk index a2e1da1011253..1c09fe64c10c6 100644 --- a/ports/stm/boards/thunderpack_v12/mpconfigboard.mk +++ b/ports/stm/boards/thunderpack_v12/mpconfigboard.mk @@ -2,12 +2,13 @@ USB_VID = 0x239A USB_PID = 0x8071 USB_PRODUCT = "Thunderpack STM32F411" USB_MANUFACTURER = "Jeremy Gillick" -USB_DEVICES = "CDC,MSC" + +# Turn off HID devices +CIRCUITPY_USB_HID = 0 LONGINT_IMPL = NONE SPI_FLASH_FILESYSTEM = 1 -EXTERNAL_FLASH_DEVICE_COUNT = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C CIRCUITPY_NVM = 1 diff --git a/ports/stm/common-hal/analogio/AnalogIn.c b/ports/stm/common-hal/analogio/AnalogIn.c index 588d687ee1348..35010ac7c54aa 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 910092897e4a8..c8e3e0868d328 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 69c1f3e0455a8..1a3817a35dbbe 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 46312b4609b5d..3c208a6118c32 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/audiopwmio/PWMAudioOut.c b/ports/stm/common-hal/audiopwmio/PWMAudioOut.c new file mode 100644 index 0000000000000..e5c478e6322b7 --- /dev/null +++ b/ports/stm/common-hal/audiopwmio/PWMAudioOut.c @@ -0,0 +1,376 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include + +#include "py/runtime.h" +#include "common-hal/audiopwmio/PWMAudioOut.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" + +#include "timers.h" + +// TODO: support multiple concurrently active outputs. +STATIC TIM_HandleTypeDef tim_handle; +STATIC audiopwmio_pwmaudioout_obj_t *active_audio = NULL; + +STATIC void set_pin(uint8_t channel, GPIO_PinState state) { + HAL_GPIO_WritePin(pin_port(active_audio->pin[channel]->port), + pin_mask(active_audio->pin[channel]->number), state); +} + +STATIC void toggle_pin(uint8_t channel) { + HAL_GPIO_TogglePin(pin_port(active_audio->pin[channel]->port), + pin_mask(active_audio->pin[channel]->number)); +} + +STATIC void set_drive_mode(const mcu_pin_obj_t *pin, uint32_t mode) { + GPIO_InitTypeDef GPIO_InitStruct = {0}; + GPIO_InitStruct.Pin = pin_mask(pin->number); + GPIO_InitStruct.Mode = mode; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + HAL_GPIO_Init(pin_port(pin->port), &GPIO_InitStruct); +} + +STATIC void start_timer(audiopwmio_pwmaudioout_obj_t *self) { + if (self->buffer_ptr[0] >= self->buffer_length[0]) { // no more pulses + return; + } + + self->period = self->buffer[0][self->buffer_ptr[0]]; + if (self->pin[1] && self->period > self->buffer[1][self->buffer_ptr[1]]) { + self->period = self->buffer[1][self->buffer_ptr[1]]; + } + + // Set the new period + tim_handle.Init.Period = self->period - 1; + HAL_TIM_Base_Init(&tim_handle); + + // TIM7 has limited HAL support, set registers manually + tim_handle.Instance->SR = 0; // Prevent the SR from triggering an interrupt + tim_handle.Instance->CR1 |= TIM_CR1_CEN; // Resume timer + tim_handle.Instance->CR1 |= TIM_CR1_URS; // Disable non-overflow interrupts + __HAL_TIM_ENABLE_IT(&tim_handle, TIM_IT_UPDATE); +} + +STATIC bool fill_buffers(audiopwmio_pwmaudioout_obj_t *self) { + // Naive PCM-to-PWM conversion + int16_t threshold = 0x666; // 0.05; TODO: make configurable + uint8_t *buffer; + uint32_t buffer_length; + audioio_get_buffer_result_t get_buffer_result; + + bool average = (self->sample_channel_count > 1) && !self->pin[1]; + bool replicate = (self->sample_channel_count == 1) && self->pin[1]; + int8_t effective_channels = average ? 1 : self->sample_channel_count; + + do { + get_buffer_result = audiosample_get_buffer(self->sample, false, 0, &buffer, &buffer_length); + if (get_buffer_result == GET_BUFFER_ERROR) { + return false; + } + + uint32_t num_samples = buffer_length / self->bytes_per_sample / self->sample_channel_count; + int16_t *buffer16 = (int16_t*)buffer; + + while (num_samples--) { + for (int8_t channel=0; channel < effective_channels; channel++) { + int16_t val; + if (self->bytes_per_sample == 1) { + val = *buffer++ << 8; + } else { + val = *buffer16++; + } + val += self->sample_offset; + + if (average) { + int16_t next; + if (self->bytes_per_sample == 1) { + next = *buffer++ << 8; + } else { + next = *buffer16++; + } + next += self->sample_offset; + val += (next - val) / 2; + } + + int8_t new_pos = (val > threshold) - (val < -threshold); + if (new_pos == -self->pos[channel]) { + if (self->len[channel] > 1) { + self->buffer[channel][self->buffer_length[channel]++] = self->len[channel]; + if (replicate) { + self->buffer[1-channel][self->buffer_length[1-channel]++] = self->len[channel]; + } + self->len[channel] = 0; + } + self->pos[channel] = new_pos; + } + self->len[channel]++; + } + } + } while (get_buffer_result == GET_BUFFER_MORE_DATA && + (!self->buffer_length[0] || (self->pin[1] && !self->buffer_length[1]))); + + if (get_buffer_result == GET_BUFFER_DONE) { + // It's the final countdown + for (int8_t channel=0; channel < effective_channels; channel++) { + self->buffer[channel][self->buffer_length[channel]++] = self->len[channel]; + if (replicate) { + self->buffer[1-channel][self->buffer_length[1-channel]++] = self->len[channel]; + } + } + + if (self->loop) { + audiosample_reset_buffer(self->sample, false, 0); + } else { + self->stopping = true; + } + } + return true; +} + +STATIC void move_to_beginning(uint16_t *buffer, uint16_t *buffer_length, uint16_t *buffer_ptr) { + if (*buffer_ptr < *buffer_length) { + memmove(buffer, buffer + *buffer_ptr, *buffer_length - *buffer_ptr); + *buffer_length -= *buffer_ptr; + } else { + *buffer_length = 0; + } + *buffer_ptr = 0; +} + +STATIC void pwmaudioout_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) + { + __HAL_TIM_CLEAR_IT(&tim_handle, TIM_IT_UPDATE); + if (!active_audio || active_audio->paused) { + __HAL_TIM_DISABLE_IT(&tim_handle, TIM_IT_UPDATE); + return; + } + + bool refill = false; + + active_audio->buffer[0][active_audio->buffer_ptr[0]] -= active_audio->period; + if (!active_audio->buffer[0][active_audio->buffer_ptr[0]]) { + toggle_pin(0); + if (++(active_audio->buffer_ptr[0]) >= active_audio->buffer_length[0]) { + refill = true; + } + } + if (active_audio->pin[1]) { + active_audio->buffer[1][active_audio->buffer_ptr[1]] -= active_audio->period; + if (!active_audio->buffer[1][active_audio->buffer_ptr[1]]) { + toggle_pin(1); + if (++(active_audio->buffer_ptr[1]) >= active_audio->buffer_length[1]) { + refill = true; + } + } + } + + if (refill) { + __HAL_TIM_DISABLE_IT(&tim_handle, TIM_IT_UPDATE); + + move_to_beginning(active_audio->buffer[0], &active_audio->buffer_length[0], &active_audio->buffer_ptr[0]); + if (active_audio->pin[1]) { + move_to_beginning(active_audio->buffer[1], &active_audio->buffer_length[1], &active_audio->buffer_ptr[1]); + } + + if (active_audio->stopping || !fill_buffers(active_audio)) { + // No more audio. Turn off output and don't restart. + common_hal_audiopwmio_pwmaudioout_stop(active_audio); + return; + } + } + + // Count up to the next given value. + start_timer(active_audio); + } + } +} + +void audiopwmout_reset() { + if (active_audio) { + common_hal_audiopwmio_pwmaudioout_stop(active_audio); + } +} + +// 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) { + + // Set up the pin(s) for output + self->pin[0] = left_channel; + self->pin[1] = right_channel; + set_drive_mode(left_channel, GPIO_MODE_OUTPUT_PP); + if (right_channel) { + set_drive_mode(right_channel, GPIO_MODE_OUTPUT_PP); + } + + self->buffer[0] = NULL; + self->buffer[1] = NULL; + + self->quiescent_value = quiescent_value; +} + +bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t *self) { + return !self->pin[0]; +} + +STATIC void free_buffers(audiopwmio_pwmaudioout_obj_t *self) { + m_free(self->buffer[0]); + self->buffer[0] = NULL; + m_free(self->buffer[1]); + self->buffer[1] = NULL; +} + +void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t *self) { + if (common_hal_audiopwmio_pwmaudioout_deinited(self)) { + return; + } + common_hal_audiopwmio_pwmaudioout_stop(self); + + free_buffers(self); + + self->pin[0] = 0; + self->pin[1] = 0; +} + +void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, mp_obj_t sample, bool loop) { + common_hal_audiopwmio_pwmaudioout_stop(self); + if (active_audio) { + mp_raise_RuntimeError(translate("Another PWMAudioOut is already active")); // TODO + } + self->sample = sample; + self->loop = loop; + + uint32_t sample_rate = audiosample_sample_rate(sample); + self->bytes_per_sample = audiosample_bits_per_sample(sample) / 8; + + uint32_t max_buffer_length; + uint8_t spacing; + bool single_buffer; + bool samples_signed; + audiosample_get_buffer_structure(sample, /* single channel */ false, + &single_buffer, &samples_signed, &max_buffer_length, &spacing); + self->sample_channel_count = audiosample_channel_count(sample); + self->sample_offset = (samples_signed ? 0x8000 : 0) - self->quiescent_value; + + free_buffers(self); + + if (max_buffer_length > UINT16_MAX) { + mp_raise_ValueError_varg(translate("Buffer length %d too big. It must be less than %d"), max_buffer_length, UINT16_MAX); + } + uint16_t buffer_length = (uint16_t)max_buffer_length / self->bytes_per_sample; + self->buffer[0] = m_malloc(buffer_length * sizeof(uint16_t), false); + self->buffer_ptr[0] = self->buffer_length[0] = 0; + if (self->pin[1]) { + self->buffer[1] = m_malloc(buffer_length * sizeof(uint16_t), false); + self->buffer_ptr[1] = self->buffer_length[1] = 0; + } + + self->pos[0] = self->pos[1] = 1; // initially on + self->len[0] = self->len[1] = 0; + + audiosample_reset_buffer(self->sample, false, 0); + self->stopping = false; + self->paused = false; + if (!fill_buffers(self)) { + mp_raise_RuntimeError(translate("Failed to buffer the sample")); + } + + // Calculate period (TODO: supersample to 1 MHz?) + TIM_TypeDef *tim_instance = stm_peripherals_find_timer(); + uint32_t source = stm_peripherals_timer_get_source_freq(tim_instance); + uint32_t prescaler = source/sample_rate; + + // Activate timer + active_audio = self; + stm_peripherals_timer_reserve(tim_instance); + stm_peripherals_timer_preinit(tim_instance, 4, pwmaudioout_event_handler); + + tim_handle.Instance = tim_instance; + 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; + tim_handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + + HAL_TIM_Base_Init(&tim_handle); + tim_handle.Instance->SR = 0; + + // Alternate on and off, starting with on. + set_pin(0, GPIO_PIN_SET); + if (self->pin[1]) { + set_pin(1, GPIO_PIN_SET); + } + + // Count up to the next given value. + start_timer(self); +} + +void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t *self) { + if (active_audio != self) { + return; + } + + // Turn off timer counter. + tim_handle.Instance->CR1 &= ~TIM_CR1_CEN; + stm_peripherals_timer_free(tim_handle.Instance); + + active_audio = NULL; + self->stopping = false; + self->paused = false; + + // Make sure pins are left low. + set_pin(0, GPIO_PIN_RESET); + if (self->pin[1]) { + set_pin(1, GPIO_PIN_RESET); + } + + // Cannot free buffers here because we may be called from + // the interrupt handler, and the heap is not reentrant. +} + +bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t *self) { + return active_audio == self; +} + +void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t *self) { + self->paused = true; +} + +void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t *self) { + self->paused = false; + if (active_audio == self) { + start_timer(self); + } +} + +bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t *self) { + return self->paused; +} diff --git a/ports/stm/common-hal/audiopwmio/PWMAudioOut.h b/ports/stm/common-hal/audiopwmio/PWMAudioOut.h new file mode 100644 index 0000000000000..bff0bfc89fabf --- /dev/null +++ b/ports/stm/common-hal/audiopwmio/PWMAudioOut.h @@ -0,0 +1,58 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_STM_COMMON_HAL_AUDIOPWM_AUDIOOUT_H +#define MICROPY_INCLUDED_STM_COMMON_HAL_AUDIOPWM_AUDIOOUT_H + +#include "common-hal/microcontroller/Pin.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t *pin[2]; + uint16_t quiescent_value; + + uint16_t *buffer[2]; + uint16_t buffer_length[2]; + uint16_t buffer_ptr[2]; + + mp_obj_t *sample; + int16_t sample_offset; + uint8_t sample_channel_count; + uint8_t bytes_per_sample; + + // PCM-to-PWM conversion state + int8_t pos[2]; // -1 for off, +1 for on + uint16_t len[2]; + + uint16_t period; + bool stopping; + bool paused; + bool loop; +} audiopwmio_pwmaudioout_obj_t; + +void audiopwmout_reset(void); + +#endif diff --git a/ports/stm/common-hal/audiopwmio/__init__.c b/ports/stm/common-hal/audiopwmio/__init__.c new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/ports/stm/common-hal/busio/I2C.c b/ports/stm/common-hal/busio/I2C.c index de69da211a734..db6d86c3423f4 100644 --- a/ports/stm/common-hal/busio/I2C.c +++ b/ports/stm/common-hal/busio/I2C.c @@ -61,10 +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); 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 { @@ -75,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; @@ -106,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) { @@ -136,6 +137,10 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, i2c_clock_enable(1 << (self->sda->periph_index - 1)); reserved_i2c[self->sda->periph_index - 1] = true; + // Create root pointer and assign IRQ + MP_STATE_PORT(cpy_i2c_obj_all)[self->sda->periph_index - 1] = self; + i2c_assign_irq(self, I2Cx); + // Handle the HAL handle differences #if (CPY_STM32H7 || CPY_STM32F7) if (frequency == 400000) { @@ -163,6 +168,13 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, } common_hal_mcu_pin_claim(sda); common_hal_mcu_pin_claim(scl); + + self->frame_in_prog = false; + + // 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); } void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { @@ -203,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); @@ -228,16 +240,45 @@ 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) { - HAL_StatusTypeDef result = HAL_I2C_Master_Transmit(&(self->handle), (uint16_t)(addr << 1), - (uint8_t *)data, (uint16_t)len, 500); + const uint8_t *data, size_t len, bool transmit_stop_bit) { + HAL_StatusTypeDef result; + if (!transmit_stop_bit) { + uint32_t xfer_opt; + if (!self->frame_in_prog) { + xfer_opt = I2C_FIRST_FRAME; + } else { + // handle rare possibility of multiple restart writes in a row + 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) { + 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); + } 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) { - return HAL_I2C_Master_Receive(&(self->handle), (uint16_t)(addr<<1), data, (uint16_t)len, 500) - == HAL_OK ? 0 : MP_EIO; + 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; + } 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) { + RUN_BACKGROUND_TASKS; + } + self->frame_in_prog = false; + return result; + } } STATIC void i2c_clock_enable(uint8_t mask) { @@ -294,3 +335,48 @@ STATIC void i2c_clock_disable(uint8_t mask) { } #endif } + +STATIC void i2c_assign_irq(busio_i2c_obj_t *self, I2C_TypeDef *I2Cx) { + #ifdef I2C1 + if (I2Cx == I2C1) { + self->irq = I2C1_EV_IRQn; + } + #endif + #ifdef I2C2 + if (I2Cx == I2C2) { + self->irq = I2C2_EV_IRQn; + } + #endif + #ifdef I2C3 + if (I2Cx == I2C3) { + self->irq = I2C3_EV_IRQn; + } + #endif + #ifdef I2C4 + if (I2Cx == I2C4) { + self->irq = I2C4_EV_IRQn; + } + #endif +} + +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]; + if (context != NULL) { + HAL_NVIC_ClearPendingIRQ(context->irq); + HAL_I2C_EV_IRQHandler(&context->handle); + } +} + +void I2C1_EV_IRQHandler(void) { + call_hal_irq(1); +} +void I2C2_EV_IRQHandler(void) { + call_hal_irq(2); +} +void I2C3_EV_IRQHandler(void) { + call_hal_irq(3); +} +void I2C4_EV_IRQHandler(void) { + call_hal_irq(4); +} diff --git a/ports/stm/common-hal/busio/I2C.h b/ports/stm/common-hal/busio/I2C.h index 5ca2854eb81a0..687e6a8c4d725 100644 --- a/ports/stm/common-hal/busio/I2C.h +++ b/ports/stm/common-hal/busio/I2C.h @@ -37,6 +37,8 @@ typedef struct { mp_obj_base_t base; I2C_HandleTypeDef handle; + IRQn_Type irq; + bool frame_in_prog; bool has_lock; const mcu_periph_obj_t *scl; const mcu_periph_obj_t *sda; diff --git a/ports/stm/common-hal/busio/SPI.c b/ports/stm/common-hal/busio/SPI.c index 20ee0f6e15790..2f26a01cba7e3 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 0cd90618198d2..ecaee84d3fc91 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,14 +259,17 @@ 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) { + reserved_uart[i] = false; never_reset_uart[i] = false; break; } @@ -293,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; } } @@ -323,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; } @@ -339,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; } @@ -363,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) { @@ -374,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; @@ -390,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")); } @@ -406,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) { @@ -429,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); @@ -608,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 52d5cad1fe639..091421fd1e14c 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 3157d0a036416..16bb8fd1e4d82 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 09456d39dd04b..23634eba69ceb 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 a676aeb155734..fbefdb79ab8a1 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 fd07d38af4fa2..d36d8ad64a4c6 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, uint32_t frequency) { 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 37c202d86ecf0..80cb9defc84f2 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 f461d3813fdec..4a33979421136 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 dd04c56dce730..b33d96e73699b 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 a827399ccb05f..28e06c9135545 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 c8852403b2bfe..f5dabe7f995a8 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 b7a1ff0351e19..6ef2eb3928d5e 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 b6ea36de3f9c7..b88d9197646d2 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 8da7243a307a5..66dfd9f768428 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 015ee8536d568..ece02f66a8f60 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 34d0cc731ae37..8de60b9cd527b 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 963aee721ac37..9e28002a69098 100644 --- a/ports/stm/common-hal/pulseio/PulseOut.c +++ b/ports/stm/common-hal/pulseio/PulseOut.c @@ -45,9 +45,9 @@ 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; -pulseio_pulseout_obj_t *curr_pulseout = NULL; +STATIC pulseio_pulseout_obj_t *curr_pulseout = NULL; STATIC void turn_on(pulseio_pulseout_obj_t *pulseout) { @@ -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 85427185e52af..beb6e44aa4e0d 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 bool 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) { @@ -58,9 +58,8 @@ STATIC void timer_get_optimal_divisors(uint32_t*period, uint32_t*prescaler, break; } } - if (*prescaler == 0) { - mp_raise_ValueError(translate("Invalid frequency supplied")); - } + // Return success or failure. + return *prescaler != 0; } void pwmout_reset(void) { @@ -75,12 +74,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 +88,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,17 +136,15 @@ 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 - if (tim_chan_taken) { - mp_raise_ValueError(translate("No more timers available on this pin.")); - } else if (tim_taken_internal) { - mp_raise_ValueError(translate("Timer was reserved for internal use - declare PWM pins earlier in the program")); + } else { // no match found + if (tim_chan_taken || tim_taken_internal) { + return PWMOUT_ALL_TIMERS_ON_PIN_IN_USE; } else if (tim_taken_f_mismatch) { - mp_raise_ValueError(translate("Frequency must match existing PWMOut using this timer")); + return PWMOUT_INVALID_FREQUENCY_ON_PIN; } else if (var_freq_mismatch) { - mp_raise_ValueError(translate("Cannot vary frequency on a timer that is already in use")); + return PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE; } else { - mp_raise_ValueError(translate("Invalid pins for PWMOut")); + return PWMOUT_INVALID_PIN; } } @@ -161,15 +158,17 @@ 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); + if (!timer_get_optimal_divisors(&period, &prescaler, frequency, source_freq)) { + return PWMOUT_INVALID_FREQUENCY; + } - //Timer init + // Timer init self->handle.Instance = TIMx; self->handle.Init.Period = period - 1; self->handle.Init.Prescaler = prescaler - 1; @@ -177,10 +176,10 @@ 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")); + return PWMOUT_INITIALIZATION_ERROR; } } @@ -190,10 +189,10 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, self->chan_handle.OCPolarity = TIM_OCPOLARITY_HIGH; self->chan_handle.OCFastMode = TIM_OCFAST_DISABLE; if (HAL_TIM_PWM_ConfigChannel(&self->handle, &self->chan_handle, self->channel) != HAL_OK) { - mp_raise_ValueError(translate("Could not initialize channel")); + return PWMOUT_INITIALIZATION_ERROR; } if (HAL_TIM_PWM_Start(&self->handle, self->channel) != HAL_OK) { - mp_raise_ValueError(translate("Could not start PWM")); + return PWMOUT_INITIALIZATION_ERROR; } self->variable_frequency = variable_frequency; @@ -215,7 +214,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 +222,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 +239,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 +248,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 +269,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 +295,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 5d8001202c847..4cf2b1c6708b0 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 2826cf53e9779..4c0ad94b07944 100644 --- a/ports/stm/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/stm/common-hal/rgbmatrix/RGBMatrix.c @@ -33,25 +33,25 @@ extern void _PM_IRQ_HANDLER(void); -void *common_hal_rgbmatrix_timer_allocate() { - TIM_TypeDef * timer = stm_peripherals_find_timer(); +void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self) { + 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 323878d20270c..cc4b82da0a992 100644 --- a/ports/stm/common-hal/rgbmatrix/RGBMatrix.h +++ b/ports/stm/common-hal/rgbmatrix/RGBMatrix.h @@ -27,9 +27,11 @@ #ifndef MICROPY_INCLUDED_STM_COMMON_HAL_RGBMATRIX_RGBMATRIX_H #define MICROPY_INCLUDED_STM_COMMON_HAL_RGBMATRIX_RGBMATRIX_H -void *common_hal_rgbmatrix_timer_allocate(void); -void common_hal_rgbmatrix_timer_enable(void*); -void common_hal_rgbmatrix_timer_disable(void*); -void common_hal_rgbmatrix_timer_free(void*); +#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 *); #endif diff --git a/ports/stm/common-hal/sdioio/SDCard.c b/ports/stm/common-hal/sdioio/SDCard.c index de0e8d11194ce..e09e2e1b3b6a8 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 c4b6c636731dc..26cba88a03c4e 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 78ee4f3e605d4..5600810138fde 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 19ae03e0b3dd0..106ff6c54016e 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 3103a071606ec..666e2c50db46b 100644 --- a/ports/stm/supervisor/port.c +++ b/ports/stm/supervisor/port.c @@ -32,6 +32,9 @@ #include "common-hal/microcontroller/Pin.h" +#ifdef CIRCUITPY_AUDIOPWMIO +#include "common-hal/audiopwmio/PWMAudioOut.h" +#endif #if CIRCUITPY_BUSIO #include "common-hal/busio/I2C.h" #include "common-hal/busio/SPI.h" @@ -98,14 +101,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 +136,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 +159,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 +176,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 +232,27 @@ void SysTick_Handler(void) { void reset_port(void) { reset_all_pins(); -#if CIRCUITPY_BUSIO + #if CIRCUITPY_AUDIOPWMIO + audiopwmout_reset(); + #endif + #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 +296,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 +330,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 +374,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 +426,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 +440,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 +452,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 f3915273b38b9..330e27dbd237e 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 3a058ed2e1be3..ac6f69bbb4b0a 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 c0e012cc625e9..906d07f737e8e 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 06af3bf1e362a..38608b5dac7ec 100644 --- a/ports/stm/tools/parse_af_csv.py +++ b/ports/stm/tools/parse_af_csv.py @@ -36,40 +36,43 @@ 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 @@ def evaluate_tim(inper, inlist, altfn, pin): 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 @@ def evaluate_tim(inper, inlist, altfn, pin): 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 @@ def evaluate_tim(inper, inlist, altfn, pin): # 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 @@ def evaluate_tim(inper, inlist, altfn, pin): # 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 @@ def evaluate_tim(inper, inlist, altfn, pin): 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 68f6db586e1ab..972c6b6a88b8a 100644 --- a/ports/stm/tools/parse_pins_csv.py +++ b/ports/stm/tools/parse_pins_csv.py @@ -33,7 +33,7 @@ # 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 @@ 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/Makefile b/ports/unix/Makefile index 305c0549d1d11..bb900a29b3f05 100644 --- a/ports/unix/Makefile +++ b/ports/unix/Makefile @@ -76,6 +76,9 @@ LDFLAGS_ARCH = -Wl,-Map=$@.map,--cref -Wl,--gc-sections endif LDFLAGS = -Lbuild $(LDFLAGS_MOD) $(LDFLAGS_ARCH) -lm $(LDFLAGS_EXTRA) +# Flags to link with pthread library +LIBPTHREAD = -lpthread + ifeq ($(MICROPY_FORCE_32BIT),1) # Note: you may need to install i386 versions of dependency packages, # starting with linux-libc-dev:i386 @@ -101,17 +104,17 @@ SRC_MOD += modusocket.c endif ifeq ($(MICROPY_PY_THREAD),1) CFLAGS_MOD += -DMICROPY_PY_THREAD=1 -DMICROPY_PY_THREAD_GIL=0 -LDFLAGS_MOD += -lpthread +LDFLAGS_MOD += $(LIBPTHREAD) endif ifeq ($(MICROPY_PY_FFI),1) ifeq ($(MICROPY_STANDALONE),1) -LIBFFI_CFLAGS_MOD := -I$(shell ls -1d $(TOP)/lib/libffi/build_dir/out/lib/libffi-*/include) +LIBFFI_CFLAGS_MOD := -I$(shell ls -1d $(BUILD)/lib/libffi/out/lib/libffi-*/include) ifeq ($(MICROPY_FORCE_32BIT),1) - LIBFFI_LDFLAGS_MOD = $(TOP)/lib/libffi/build_dir/out/lib32/libffi.a + LIBFFI_LDFLAGS_MOD = $(BUILD)/lib/libffi/out/lib32/libffi.a else - LIBFFI_LDFLAGS_MOD = $(TOP)/lib/libffi/build_dir/out/lib/libffi.a + LIBFFI_LDFLAGS_MOD = $(BUILD)/lib/libffi/out/lib/libffi.a endif else LIBFFI_CFLAGS_MOD := $(shell pkg-config --cflags libffi) @@ -141,7 +144,6 @@ SRC_C += \ mpthreadport.c \ input.c \ file.c \ - modmachine.c \ modos.c \ moduos_vfs.c \ modtime.c \ @@ -156,12 +158,6 @@ SRC_C += \ supervisor/shared/translate.c \ $(SRC_MOD) -PY_EXTMOD_O_BASENAME += \ - extmod/machine_mem.o \ - extmod/machine_pinbase.o \ - extmod/machine_signal.o \ - extmod/machine_pulse.o \ - LIB_SRC_C = $(addprefix lib/,\ $(LIB_SRC_C_EXTRA) \ timeutils/timeutils.c \ @@ -232,8 +228,7 @@ nanbox: CFLAGS_EXTRA='-DMP_CONFIGFILE=""' \ BUILD=build-nanbox \ PROG=micropython_nanbox \ - MICROPY_FORCE_32BIT=1 \ - MICROPY_PY_USSL=0 + MICROPY_FORCE_32BIT=1 freedos: $(MAKE) \ @@ -264,9 +259,9 @@ coverage: coverage_test: coverage $(eval DIRNAME=ports/$(notdir $(CURDIR))) - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs -d thread - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests --auto-jobs --emit native + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 -d thread + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 --emit native cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/micropython_coverage ./run-tests -j1 --via-mpy -d basics float cat $(TOP)/tests/basics/0prelim.py | ./micropython_coverage | grep -q 'abc' gcov -o build-coverage/py $(TOP)/py/*.c @@ -297,23 +292,19 @@ endif deplibs: libffi axtls +libffi: $(BUILD)/lib/libffi/include/ffi.h + +$(TOP)/lib/libffi/configure: $(TOP)/lib/libffi/autogen.sh + cd $(TOP)/lib/libffi; ./autogen.sh + # install-exec-recursive & install-data-am targets are used to avoid building # docs and depending on makeinfo -libffi: - cd $(TOP)/lib/libffi; git clean -d -x -f - cd $(TOP)/lib/libffi; ./autogen.sh - mkdir -p $(TOP)/lib/libffi/build_dir; cd $(TOP)/lib/libffi/build_dir; \ - ../configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out --disable-structs CC="$(CC)" CXX="$(CXX)" LD="$(LD)" CFLAGS="-Os -fomit-frame-pointer -fstrict-aliasing -ffast-math -fno-exceptions"; \ +$(BUILD)/lib/libffi/include/ffi.h: $(TOP)/lib/libffi/configure + mkdir -p $(BUILD)/lib/libffi; cd $(BUILD)/lib/libffi; \ + $(abspath $(TOP))/lib/libffi/configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out --disable-structs CC="$(CC)" CXX="$(CXX)" LD="$(LD)" CFLAGS="-Os -fomit-frame-pointer -fstrict-aliasing -ffast-math -fno-exceptions"; \ $(MAKE) install-exec-recursive; $(MAKE) -C include install-data-am -axtls: $(BUILD)/libaxtls.a - -$(BUILD)/libaxtls.a: $(TOP)/lib/axtls/README | $(OBJ_DIRS) - cd $(TOP)/lib/axtls; cp config/upyconfig config/.config - cd $(TOP)/lib/axtls; $(MAKE) oldconfig -B - cd $(TOP)/lib/axtls; $(MAKE) clean - cd $(TOP)/lib/axtls; $(MAKE) all CC="$(CC)" LD="$(LD)" - cp $(TOP)/lib/axtls/_stage/libaxtls.a $@ +axtls: $(TOP)/lib/axtls/README $(TOP)/lib/axtls/README: @echo "You cloned without --recursive, fetching submodules for you." diff --git a/ports/unix/alloc.c b/ports/unix/alloc.c index ca12d025b64b1..7fe7b4dba4e71 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 849820fffde9b..2d377bc8fe5ad 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 222dca462183b..745593c81c9f5 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; @@ -125,6 +125,8 @@ STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i o->fd = -1; #endif return 0; + case MP_STREAM_GET_FILENO: + return o->fd; default: *errcode = EINVAL; return MP_STREAM_ERROR; @@ -175,7 +177,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 +185,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 +246,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 +266,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 +278,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 7cd74ec1349b6..45ad1e04300d2 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 b661ce3e242b9..6fbb8513accd3 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 5a3cbaf477d6e..715ad56589970 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,29 +490,26 @@ 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); - } - 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); + 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; } - p = p1 + 1; } - } - - - mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0); @@ -613,7 +610,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 +659,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 c750f2eb77d86..894702330fb6d 100644 --- a/ports/unix/modffi.c +++ b/ports/unix/modffi.c @@ -93,39 +93,54 @@ 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; + case 'q': + return &ffi_type_sint64; + case 'Q': + return &ffi_type_uint64; #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 +153,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 +166,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 +203,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 +240,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 +261,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 +353,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 +378,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 +391,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 +456,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 +483,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 +502,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 +518,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 82d1ccd559426..3ff5c61f50a5d 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)) { @@ -118,7 +118,7 @@ STATIC void print_jobject(const mp_print_t *print, jobject obj) { // jclass STATIC void jclass_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); if (kind == PRINT_REPR) { mp_printf(print, "cls); } @@ -131,7 +131,7 @@ STATIC void jclass_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // load attribute - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); const char *attr = qstr_str(attr_in); jstring field_name = JJ(NewStringUTF, attr); @@ -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); @@ -151,7 +151,7 @@ STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { o->meth = NULL; o->obj = self->cls; o->is_static = true; - dest[0] = o; + dest[0] = MP_OBJ_FROM_PTR(o); } } @@ -159,7 +159,7 @@ STATIC mp_obj_t jclass_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const if (n_kw != 0) { mp_raise_TypeError("kwargs not supported"); } - mp_obj_jclass_t *self = self_in; + mp_obj_jclass_t *self = MP_OBJ_TO_PTR(self_in); jarray methods = JJ(CallObjectMethod, self->cls, Class_getConstructors_mid); @@ -179,20 +179,20 @@ 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) { mp_obj_jclass_t *o = m_new_obj(mp_obj_jclass_t); o->base.type = &jclass_type; o->cls = jc; - return o; + return MP_OBJ_FROM_PTR(o); } // jobject STATIC void jobject_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); if (kind == PRINT_REPR) { mp_printf(print, "obj); } @@ -205,7 +205,7 @@ STATIC void jobject_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // load attribute - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); const char *attr = qstr_str(attr_in); jclass obj_class = JJ(GetObjectClass, self->obj); @@ -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); @@ -229,7 +229,7 @@ STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { o->meth = NULL; o->obj = self->obj; o->is_static = false; - dest[0] = o; + dest[0] = MP_OBJ_FROM_PTR(o); } } @@ -242,11 +242,11 @@ STATIC void get_jclass_name(jobject obj, char *buf) { } STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); 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,11 +288,11 @@ 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) { - mp_obj_jobject_t *self = self_in; + mp_obj_jobject_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { case MP_UNARY_OP_BOOL: case MP_UNARY_OP_LEN: { @@ -316,9 +316,9 @@ MP_DEFINE_CONST_FUN_OBJ_2(subscr_load_adaptor_obj, subscr_load_adaptor); // .getiter special method which returns iterator which works in terms // of object subscription. -STATIC mp_obj_t subscr_getiter(mp_obj_t self_in) { - mp_obj_t dest[2] = {(mp_obj_t)&subscr_load_adaptor_obj, self_in}; - return mp_obj_new_getitem_iter(dest); +STATIC mp_obj_t subscr_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { + mp_obj_t dest[2] = {MP_OBJ_FROM_PTR(&subscr_load_adaptor_obj), self_in}; + return mp_obj_new_getitem_iter(dest, iter_buf); } STATIC const mp_obj_type_t jobject_type = { @@ -346,7 +346,7 @@ STATIC mp_obj_t new_jobject(jobject jo) { mp_obj_jobject_t *o = m_new_obj(mp_obj_jobject_t); o->base.type = &jobject_type; o->obj = jo; - return o; + return MP_OBJ_FROM_PTR(o); } } @@ -356,7 +356,7 @@ STATIC mp_obj_t new_jobject(jobject jo) { STATIC void jmethod_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; - mp_obj_jmethod_t *self = self_in; + mp_obj_jmethod_t *self = MP_OBJ_TO_PTR(self_in); // Variable value printed as cast to int mp_printf(print, "", qstr_str(self->name)); } @@ -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) { @@ -408,11 +408,11 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { if (!is_object) { return false; } - mp_obj_jobject_t *jo = arg; + mp_obj_jobject_t *jo = MP_OBJ_TO_PTR(arg); 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; } } @@ -490,8 +490,8 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool // printf("name=%p meth_name=%s\n", name, meth_name); bool found = true; - for (int i = 0; i < n_args && *arg_types != ')'; i++) { - if (!py2jvalue(&arg_types, args[i], &jargs[i])) { + for (size_t j = 0; j < n_args && *arg_types != ')'; j++) { + if (!py2jvalue(&arg_types, args[j], &jargs[j])) { goto next_method; } @@ -507,13 +507,12 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool if (found) { // printf("found!\n"); jmethodID method_id = JJ(FromReflectedMethod, meth); - jobject res; - mp_obj_t ret; if (is_constr) { JJ(ReleaseStringUTFChars, name_o, decl); - res = JJ(NewObjectA, obj, method_id, jargs); + jobject res = JJ(NewObjectA, obj, method_id, jargs); return new_jobject(res); } else { + mp_obj_t ret; if (MATCH(ret_type, "void")) { JJ(CallVoidMethodA, obj, method_id, jargs); check_exception(); @@ -527,7 +526,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool check_exception(); ret = mp_obj_new_bool(res); } else if (is_object_type(ret_type)) { - res = JJ(CallObjectMethodA, obj, method_id, jargs); + jobject res = JJ(CallObjectMethodA, obj, method_id, jargs); check_exception(); ret = new_jobject(res); } else { @@ -542,7 +541,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); @@ -556,7 +555,7 @@ STATIC mp_obj_t jmethod_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const if (n_kw != 0) { mp_raise_TypeError("kwargs not supported"); } - mp_obj_jmethod_t *self = self_in; + mp_obj_jmethod_t *self = MP_OBJ_TO_PTR(self_in); const char *name = qstr_str(self->name); // jstring meth_name = JJ(NewStringUTF, name); @@ -585,7 +584,7 @@ STATIC const mp_obj_type_t jmethod_type = { #define LIBJVM_SO "libjvm.so" #endif -STATIC void create_jvm() { +STATIC void create_jvm(void) { JavaVMInitArgs args; JavaVMOption options; options.optionString = "-Djava.class.path=."; @@ -602,9 +601,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 +614,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"); } @@ -648,7 +647,7 @@ STATIC mp_obj_t mod_jni_cls(mp_obj_t cls_name_in) { mp_obj_jclass_t *o = m_new_obj(mp_obj_jclass_t); o->base.type = &jclass_type; o->cls = cls; - return o; + return MP_OBJ_FROM_PTR(o); } MP_DEFINE_CONST_FUN_OBJ_1(mod_jni_cls_obj, mod_jni_cls); @@ -661,7 +660,7 @@ STATIC mp_obj_t mod_jni_array(mp_obj_t type_in, mp_obj_t size_in) { if (MP_OBJ_IS_TYPE(type_in, &jclass_type)) { - mp_obj_jclass_t *jcls = type_in; + mp_obj_jclass_t *jcls = MP_OBJ_TO_PTR(type_in); res = JJ(NewObjectArray, size, jcls->cls, NULL); } else if (MP_OBJ_IS_STR(type_in)) { @@ -700,8 +699,8 @@ STATIC mp_obj_t mod_jni_array(mp_obj_t type_in, mp_obj_t size_in) { MP_DEFINE_CONST_FUN_OBJ_2(mod_jni_array_obj, mod_jni_array); -STATIC mp_obj_t mod_jni_env() { - return mp_obj_new_int((mp_int_t)env); +STATIC mp_obj_t mod_jni_env(void) { + return mp_obj_new_int((mp_int_t)(uintptr_t)env); } MP_DEFINE_CONST_FUN_OBJ_0(mod_jni_env_obj, mod_jni_env); @@ -716,5 +715,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 61697cfb6f324..af3a9d88fe105 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 252b19a50cfaf..43d75905189fe 100644 --- a/ports/unix/modos.c +++ b/ports/unix/modos.c @@ -37,6 +37,7 @@ #include "py/runtime.h" #include "py/objtuple.h" #include "py/mphal.h" +#include "extmod/vfs.h" #include "extmod/misc.h" #ifdef __ANDROID__ @@ -106,16 +107,21 @@ STATIC mp_obj_t mod_os_statvfs(mp_obj_t path_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_statvfs_obj, mod_os_statvfs); #endif -STATIC mp_obj_t mod_os_unlink(mp_obj_t path_in) { +STATIC mp_obj_t mod_os_remove(mp_obj_t path_in) { const char *path = mp_obj_str_get_str(path_in); + // Note that POSIX requires remove() to be able to delete a directory + // too (act as rmdir()). This is POSIX extenstion to ANSI C semantics + // of that function. But Python remove() follows ANSI C, and explicitly + // required to raise exception on attempt to remove a directory. Thus, + // call POSIX unlink() here. int r = unlink(path); RAISE_ERRNO(r, errno); return mp_const_none; } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_unlink_obj, mod_os_unlink); +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_os_remove_obj, mod_os_remove); STATIC mp_obj_t mod_os_system(mp_obj_t cmd_in) { const char *cmd = mp_obj_str_get_str(cmd_in); @@ -172,12 +178,24 @@ STATIC mp_obj_t listdir_next(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(dirent->d_name, strlen(dirent->d_name)); + #ifdef _DIRENT_HAVE_D_TYPE - t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); + #ifdef DTTOIF + t->items[1] = MP_OBJ_NEW_SMALL_INT(DTTOIF(dirent->d_type)); + #else + if (dirent->d_type == DT_DIR) { + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); + } else if (dirent->d_type == DT_REG) { + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); + } else { + t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); + } + #endif #else // DT_UNKNOWN should have 0 value on any reasonable system t->items[1] = MP_OBJ_NEW_SMALL_INT(0); #endif + #ifdef _DIRENT_HAVE_D_INO t->items[2] = MP_OBJ_NEW_SMALL_INT(dirent->d_ino); #else @@ -217,7 +235,7 @@ STATIC const mp_rom_map_elem_t mp_module_os_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&mod_os_statvfs_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_system), MP_ROM_PTR(&mod_os_system_obj) }, - { MP_ROM_QSTR(MP_QSTR_unlink), MP_ROM_PTR(&mod_os_unlink_obj) }, + { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&mod_os_remove_obj) }, { MP_ROM_QSTR(MP_QSTR_getenv), MP_ROM_PTR(&mod_os_getenv_obj) }, { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&mod_os_mkdir_obj) }, { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&mod_os_ilistdir_obj) }, @@ -230,5 +248,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 fe19aac83c695..bd723085de129 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 cc9b4a337156c..94ae8d2f1e3b2 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 b45d4485b5e9d..bb2f370d9aec9 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 dbda5e1107379..d4c6a8e1790b1 100644 --- a/ports/unix/moduselect.c +++ b/ports/unix/moduselect.c @@ -34,6 +34,7 @@ #include #include "py/runtime.h" +#include "py/stream.h" #include "py/obj.h" #include "py/objlist.h" #include "py/objtuple.h" @@ -65,19 +66,15 @@ typedef struct _mp_obj_poll_t { } mp_obj_poll_t; STATIC int get_fd(mp_obj_t fdlike) { - int fd; - // Shortcut for fdfile compatible types - if (MP_OBJ_IS_TYPE(fdlike, &mp_type_fileio) - #if MICROPY_PY_SOCKET - || MP_OBJ_IS_TYPE(fdlike, &mp_type_socket) - #endif - ) { - mp_obj_fdfile_t *fdfile = MP_OBJ_TO_PTR(fdlike); - fd = fdfile->fd; - } else { - fd = mp_obj_get_int(fdlike); + if (MP_OBJ_IS_OBJ(fdlike)) { + const mp_stream_p_t *stream_p = mp_get_stream_raise(fdlike, MP_STREAM_OP_IOCTL); + int err; + mp_uint_t res = stream_p->ioctl(fdlike, MP_STREAM_GET_FILENO, 0, &err); + if (res != MP_STREAM_ERROR) { + return res; + } } - return fd; + return mp_obj_get_int(fdlike); } /// \method register(obj[, eventmask]) @@ -161,13 +158,13 @@ STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmas for (int i = self->len - 1; i >= 0; i--) { if (entries->fd == fd) { entries->events = mp_obj_get_int(eventmask_in); - break; + return mp_const_none; } entries++; } - // TODO raise KeyError if obj didn't exist in map - return mp_const_none; + // obj doesn't exist in poller + mp_raise_OSError(MP_ENOENT); } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); @@ -315,7 +312,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 +345,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 90651a19ea4c2..24778b6b55cb2 100644 --- a/ports/unix/modusocket.c +++ b/ports/unix/modusocket.c @@ -37,6 +37,7 @@ #include #include #include +#include #include "py/objtuple.h" #include "py/objstr.h" @@ -67,6 +68,7 @@ typedef struct _mp_obj_socket_t { mp_obj_base_t base; int fd; + bool blocking; } mp_obj_socket_t; const mp_obj_type_t mp_type_socket; @@ -80,6 +82,7 @@ STATIC mp_obj_socket_t *socket_new(int fd) { mp_obj_socket_t *o = m_new_obj(mp_obj_socket_t); o->base.type = &mp_type_socket; o->fd = fd; + o->blocking = true; return o; } @@ -94,7 +97,14 @@ STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errc mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); mp_int_t r = read(o->fd, buf, size); if (r == -1) { - *errcode = errno; + int err = errno; + // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO + // timed out, and need to convert that to ETIMEDOUT. + if (err == EAGAIN && o->blocking) { + err = MP_ETIMEDOUT; + } + + *errcode = err; return MP_STREAM_ERROR; } return r; @@ -104,7 +114,14 @@ STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); mp_int_t r = write(o->fd, buf, size); if (r == -1) { - *errcode = errno; + int err = errno; + // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO + // timed out, and need to convert that to ETIMEDOUT. + if (err == EAGAIN && o->blocking) { + err = MP_ETIMEDOUT; + } + + *errcode = err; return MP_STREAM_ERROR; } return r; @@ -125,6 +142,9 @@ STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i close(self->fd); return 0; + case MP_STREAM_GET_FILENO: + return self->fd; + default: *errcode = MP_EINVAL; return MP_STREAM_ERROR; @@ -168,10 +188,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 +237,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 +245,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 +285,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); @@ -309,10 +329,49 @@ STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { } flags = fcntl(self->fd, F_SETFL, flags); RAISE_ERRNO(flags, errno); + self->blocking = val; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); +STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { + mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); + struct timeval tv = {0,}; + bool new_blocking = true; + + if (timeout_in == mp_const_none) { + setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, NULL, 0); + setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, NULL, 0); + } else { + #if MICROPY_PY_BUILTINS_FLOAT + mp_float_t val = mp_obj_get_float(timeout_in); + double ipart; + tv.tv_usec = round(modf(val, &ipart) * 1000000); + tv.tv_sec = ipart; + #else + tv.tv_sec = mp_obj_get_int(timeout_in); + #endif + + // For SO_RCVTIMEO/SO_SNDTIMEO, zero timeout means infinity, but + // for Python API it means non-blocking. + if (tv.tv_sec == 0 && tv.tv_usec == 0) { + new_blocking = false; + } else { + setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, + &tv, sizeof(struct timeval)); + setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, + &tv, sizeof(struct timeval)); + } + } + + if (self->blocking != new_blocking) { + socket_setblocking(self_in, mp_obj_new_bool(new_blocking)); + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout); + STATIC mp_obj_t socket_makefile(size_t n_args, const mp_obj_t *args) { // TODO: CPython explicitly says that closing returned object doesn't close // the original socket (Python2 at all says that fd is dup()ed). But we @@ -321,7 +380,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); @@ -368,6 +427,7 @@ STATIC const mp_rom_map_elem_t usocket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socket_sendto_obj) }, { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&socket_setsockopt_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, + { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&socket_settimeout_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, }; @@ -388,7 +448,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 +502,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 +514,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 +560,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 +599,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 +623,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 d6bbad9ce1a3d..01e5876b0b1b6 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. @@ -54,7 +54,7 @@ #define MICROPY_DEBUG_PRINTERS (1) // Printing debug to stderr may give tests which // check stdout a chance to pass, etc. -#define MICROPY_DEBUG_PRINTER_DEST mp_stderr_print +#define MICROPY_DEBUG_PRINTER (&mp_stderr_print) #define MICROPY_READER_POSIX (1) #define MICROPY_USE_READLINE_HISTORY (1) #define MICROPY_HELPER_REPL (1) @@ -125,7 +125,9 @@ #define MICROPY_PY_UTIMEQ (1) #define MICROPY_PY_UHASHLIB (1) #if MICROPY_PY_USSL +#define MICROPY_PY_UHASHLIB_MD5 (1) #define MICROPY_PY_UHASHLIB_SHA1 (1) +#define MICROPY_PY_UCRYPTOLIB (1) #endif #define MICROPY_PY_UBINASCII (1) #define MICROPY_PY_UBINASCII_CRC32 (1) @@ -133,9 +135,9 @@ #ifndef MICROPY_PY_USELECT_POSIX #define MICROPY_PY_USELECT_POSIX (1) #endif -#define MICROPY_PY_WEBSOCKET (1) -#define MICROPY_PY_MACHINE (1) -#define MICROPY_PY_MACHINE_PULSE (1) +#define MICROPY_PY_WEBSOCKET (0) +#define MICROPY_PY_MACHINE (0) +#define MICROPY_PY_MACHINE_PULSE (0) #define MICROPY_MACHINE_MEM_GET_READ_ADDR mod_machine_mem_get_addr #define MICROPY_MACHINE_MEM_GET_WRITE_ADDR mod_machine_mem_get_addr @@ -189,6 +191,11 @@ extern const struct _mp_obj_module_t mp_module_jni; #else #define MICROPY_PY_FFI_DEF #endif +#if MICROPY_PY_MACHINE +#define MICROPY_PY_MACHINE_DEF { MP_ROM_QSTR(MP_QSTR_umachine), MP_ROM_PTR(&mp_module_machine) }, +#else +#define MICROPY_PY_MACHINE_DEF +#endif #if MICROPY_PY_JNI #define MICROPY_PY_JNI_DEF { MP_ROM_QSTR(MP_QSTR_jni), MP_ROM_PTR(&mp_module_jni) }, #else @@ -220,7 +227,7 @@ extern const struct _mp_obj_module_t mp_module_jni; MICROPY_PY_JNI_DEF \ MICROPY_PY_UTIME_DEF \ MICROPY_PY_SOCKET_DEF \ - { MP_ROM_QSTR(MP_QSTR_umachine), MP_ROM_PTR(&mp_module_machine) }, \ + MICROPY_PY_MACHINE_DEF \ MICROPY_PY_UOS_DEF \ MICROPY_PY_USELECT_DEF \ MICROPY_PY_TERMIOS_DEF \ @@ -250,7 +257,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) @@ -325,3 +332,4 @@ void mp_unix_mark_exec(void); #define MICROPY_PY_BUILTINS_HELP (1) #define MICROPY_PY_BUILTINS_HELP_MODULES (1) +#define CIRCUITPY_RE_DEBUG (1) diff --git a/ports/unix/mpconfigport.mk b/ports/unix/mpconfigport.mk index 6bb1c9693fe38..d0e5686024450 100644 --- a/ports/unix/mpconfigport.mk +++ b/ports/unix/mpconfigport.mk @@ -24,11 +24,11 @@ MICROPY_PY_SOCKET = 1 MICROPY_PY_FFI = 1 # ussl module requires one of the TLS libraries below -MICROPY_PY_USSL = 1 +MICROPY_PY_USSL = 0 # axTLS has minimal size and fully integrated with MicroPython, but # implements only a subset of modern TLS functionality, so may have # problems with some servers. -MICROPY_SSL_AXTLS = 1 +MICROPY_SSL_AXTLS = 0 # mbedTLS is more up to date and complete implementation, but also # more bloated. Configuring and building of mbedTLS should be done # outside of MicroPython, it can just link with mbedTLS library. diff --git a/ports/unix/mpconfigport_coverage.h b/ports/unix/mpconfigport_coverage.h index 468d69a7334db..27086a167d561 100644 --- a/ports/unix/mpconfigport_coverage.h +++ b/ports/unix/mpconfigport_coverage.h @@ -32,23 +32,32 @@ #include +#define MICROPY_OPT_MATH_FACTORIAL (1) #define MICROPY_FLOAT_HIGH_QUALITY_HASH (1) #define MICROPY_ENABLE_SCHEDULER (1) #define MICROPY_READER_VFS (1) +#define MICROPY_MODULE_GETATTR (1) #define MICROPY_PY_DELATTR_SETATTR (1) #define MICROPY_PY_REVERSE_SPECIAL_METHODS (1) #define MICROPY_PY_BUILTINS_RANGE_BINOP (1) #define MICROPY_PY_BUILTINS_HELP (1) #define MICROPY_PY_BUILTINS_HELP_MODULES (1) #define MICROPY_PY_SYS_GETSIZEOF (1) +#define MICROPY_PY_MATH_FACTORIAL (1) #define MICROPY_PY_URANDOM_EXTRA_FUNCS (1) #define MICROPY_PY_IO_BUFFEREDWRITER (1) #define MICROPY_PY_IO_RESOURCE_STREAM (1) +#define MICROPY_PY_URE_MATCH_GROUPS (1) +#define MICROPY_PY_URE_MATCH_SPAN_START_END (1) +#define MICROPY_PY_URE_SUB (1) #define MICROPY_VFS_POSIX (1) #undef MICROPY_VFS_FAT #define MICROPY_VFS_FAT (1) #define MICROPY_FATFS_USE_LABEL (1) #define MICROPY_PY_FRAMEBUF (1) +#define MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT (1) +#define MICROPY_PY_COLLECTIONS_ORDEREDDICT (1) +#define MICROPY_PY_UCRYPTOLIB (1) // TODO these should be generic, not bound to fatfs #define mp_type_fileio mp_type_vfs_posix_fileio diff --git a/ports/unix/mpconfigport_minimal.h b/ports/unix/mpconfigport_minimal.h index 1a13d5725b474..3977818b031cb 100644 --- a/ports/unix/mpconfigport_minimal.h +++ b/ports/unix/mpconfigport_minimal.h @@ -65,6 +65,8 @@ #define MICROPY_PY_BUILTINS_REVERSED (0) #define MICROPY_PY_BUILTINS_SET (0) #define MICROPY_PY_BUILTINS_SLICE (0) +#define MICROPY_PY_BUILTINS_STR_COUNT (0) +#define MICROPY_PY_BUILTINS_STR_OP_MODULO (0) #define MICROPY_PY_BUILTINS_STR_UNICODE (0) #define MICROPY_PY_BUILTINS_PROPERTY (0) #define MICROPY_PY_BUILTINS_MIN_MAX (0) diff --git a/ports/unix/mphalport.h b/ports/unix/mphalport.h index 4e459ffca5180..d852b78c0c234 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 3641745bc646d..864cf795e748a 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 77deb3152faac..ab9c08f511ecf 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 af5c81bf37a38..684fb204f0682 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -31,60 +31,65 @@ #include "supervisor/shared/translate.h" - -void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw) { - size_t n_kw = 0; - if (kw_args != NULL) { - n_kw = kw_args->used; - } - mp_arg_check_num_kw_array(n_args, n_kw, n_args_min, n_args_max, takes_kw); -} - -void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) { - // NOTE(tannewt): This prevents this function from being optimized away. - // Without it, functions can crash when reading invalid args. - __asm volatile (""); +void mp_arg_check_num_sig(size_t n_args, size_t n_kw, uint32_t sig) { // TODO maybe take the function name as an argument so we can print nicer error messages - if (n_kw > 0 && !takes_kw) { - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + // The reverse of MP_OBJ_FUN_MAKE_SIG + bool takes_kw = sig & 1; + size_t n_args_min = sig >> 17; + size_t n_args_max = (sig >> 1) & 0xffff; + + if (n_kw && !takes_kw) { + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { mp_arg_error_terse_mismatch(); - #else - mp_raise_TypeError(translate("function does not take keyword arguments")); - #endif + } else { + mp_raise_TypeError(translate("function doesn't take keyword arguments")); + } } 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 } } } +inline void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw) { + size_t n_kw = 0; + if (kw_args != NULL) { + n_kw = kw_args->used; + } + mp_arg_check_num_sig(n_args, n_kw, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw)); +} + +inline void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) { + mp_arg_check_num_sig(n_args, n_kw, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw)); +} + void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals) { size_t pos_found = 0, kws_found = 0; for (size_t i = 0; i < n_allowed; i++) { @@ -99,12 +104,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 +128,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 11e498b2c7627..871f0bb486c32 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); @@ -273,6 +273,21 @@ void asm_arm_mov_reg_local_addr(asm_arm_t *as, uint rd, int local_num) { emit_al(as, asm_arm_op_add_imm(rd, ASM_ARM_REG_SP, local_num << 2)); } +void asm_arm_mov_reg_pcrel(asm_arm_t *as, uint reg_dest, uint label) { + assert(label < as->base.max_num_labels); + mp_uint_t dest = as->base.label_offsets[label]; + mp_int_t rel = dest - as->base.code_offset; + rel -= 12 + 8; // adjust for load of rel, and then PC+8 prefetch of add_reg_reg_reg + + // To load rel int reg_dest, insert immediate into code and jump over it + emit_al(as, 0x59f0000 | (reg_dest << 12)); // ldr rd, [pc] + emit_al(as, 0xa000000); // b pc + emit(as, rel); + + // Do reg_dest += PC + asm_arm_add_reg_reg_reg(as, reg_dest, reg_dest, ASM_ARM_REG_PC); +} + void asm_arm_lsl_reg_reg(asm_arm_t *as, uint rd, uint rs) { // mov rd, rd, lsl rs emit_al(as, 0x1a00010 | (rd << 12) | (rs << 8) | rd); @@ -347,19 +362,15 @@ void asm_arm_b_label(asm_arm_t *as, uint label) { asm_arm_bcc_label(as, ASM_ARM_CC_AL, label); } -void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp) { - // If the table offset fits into the ldr instruction - if (fun_id < (0x1000 / 4)) { - emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_LR, ASM_ARM_REG_PC)); // mov lr, pc - emit_al(as, 0x597f000 | (fun_id << 2)); // ldr pc, [r7, #fun_id*4] - return; - } +void asm_arm_bl_ind(asm_arm_t *as, uint fun_id, uint reg_temp) { + // The table offset should fit into the ldr instruction + assert(fun_id < (0x1000 / 4)); + emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_LR, ASM_ARM_REG_PC)); // mov lr, pc + emit_al(as, 0x597f000 | (fun_id << 2)); // ldr pc, [r7, #fun_id*4] +} - emit_al(as, 0x59f0004 | (reg_temp << 12)); // ldr rd, [pc, #4] - // 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); +void asm_arm_bx_reg(asm_arm_t *as, uint reg_src) { + emit_al(as, 0x012fff10 | reg_src); } #endif // MICROPY_EMIT_ARM diff --git a/py/asmarm.h b/py/asmarm.h index f63106a9b6402..76850cb4684d6 100644 --- a/py/asmarm.h +++ b/py/asmarm.h @@ -98,6 +98,7 @@ void asm_arm_and_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_eor_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_orr_reg_reg_reg(asm_arm_t *as, uint rd, uint rn, uint rm); void asm_arm_mov_reg_local_addr(asm_arm_t *as, uint rd, int local_num); +void asm_arm_mov_reg_pcrel(asm_arm_t *as, uint reg_dest, uint label); void asm_arm_lsl_reg_reg(asm_arm_t *as, uint rd, uint rs); void asm_arm_asr_reg_reg(asm_arm_t *as, uint rd, uint rs); @@ -120,7 +121,11 @@ void asm_arm_pop(asm_arm_t *as, uint reglist); // control flow void asm_arm_bcc_label(asm_arm_t *as, int cond, uint label); void asm_arm_b_label(asm_arm_t *as, uint label); -void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); +void asm_arm_bl_ind(asm_arm_t *as, uint fun_id, uint reg_temp); +void asm_arm_bx_reg(asm_arm_t *as, uint reg_src); + +// Holds a pointer to mp_fun_table +#define ASM_ARM_REG_FUN_TABLE ASM_ARM_REG_R7 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -144,18 +149,21 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); #define REG_LOCAL_3 ASM_ARM_REG_R6 #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_ARM_REG_FUN_TABLE + #define ASM_T asm_arm_t #define ASM_END_PASS asm_arm_end_pass #define ASM_ENTRY asm_arm_entry #define ASM_EXIT asm_arm_exit #define ASM_JUMP asm_arm_b_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_arm_cmp_reg_i8(as, reg, 0); \ asm_arm_bcc_label(as, ASM_ARM_CC_EQ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ asm_arm_cmp_reg_i8(as, reg, 0); \ asm_arm_bcc_label(as, ASM_ARM_CC_NE, label); \ @@ -165,14 +173,15 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); asm_arm_cmp_reg_reg(as, reg1, reg2); \ asm_arm_bcc_label(as, ASM_ARM_CC_EQ, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_arm_bl_ind(as, ptr, idx, ASM_ARM_REG_R3) +#define ASM_JUMP_REG(as, reg) asm_arm_bx_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_arm_bl_ind(as, idx, ASM_ARM_REG_R3) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_arm_mov_local_reg((as), (local_num), (reg_src)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_arm_mov_reg_i32((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_arm_mov_reg_i32((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_arm_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_arm_mov_reg_reg((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_arm_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_arm_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) asm_arm_lsl_reg_reg((as), (reg_dest), (reg_shift)) #define ASM_ASR_REG_REG(as, reg_dest, reg_shift) asm_arm_asr_reg_reg((as), (reg_dest), (reg_shift)) diff --git a/py/asmbase.c b/py/asmbase.c index 4d080f095ea97..5cf8a78c26e2c 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 3b2f59d159b5d..9ee7fe061d0dc 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 3cf47c5b15508..df7c88568cf56 100644 --- a/py/asmthumb.c +++ b/py/asmthumb.c @@ -36,6 +36,8 @@ #include "py/mphal.h" #include "py/asmthumb.h" +#define UNSIGNED_FIT5(x) ((uint32_t)(x) < 32) +#define UNSIGNED_FIT7(x) ((uint32_t)(x) < 128) #define UNSIGNED_FIT8(x) (((x) & 0xffffff00) == 0) #define UNSIGNED_FIT16(x) (((x) & 0xffff0000) == 0) #define SIGNED_FIT8(x) (((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80) @@ -43,6 +45,15 @@ #define SIGNED_FIT12(x) (((x) & 0xfffff800) == 0) || (((x) & 0xfffff800) == 0xfffff800) #define SIGNED_FIT23(x) (((x) & 0xffc00000) == 0) || (((x) & 0xffc00000) == 0xffc00000) +// Note: these actually take an imm12 but the high-bit is not encoded here +#define OP_ADD_W_RRI_HI(reg_src) (0xf200 | (reg_src)) +#define OP_ADD_W_RRI_LO(reg_dest, imm11) ((imm11 << 4 & 0x7000) | reg_dest << 8 | (imm11 & 0xff)) +#define OP_SUB_W_RRI_HI(reg_src) (0xf2a0 | (reg_src)) +#define OP_SUB_W_RRI_LO(reg_dest, imm11) ((imm11 << 4 & 0x7000) | reg_dest << 8 | (imm11 & 0xff)) + +#define OP_LDR_W_HI(reg_base) (0xf8d0 | (reg_base)) +#define OP_LDR_W_LO(reg_dest, imm12) ((reg_dest) << 12 | (imm12)) + static inline byte *asm_thumb_get_cur_to_write_bytes(asm_thumb_t *as, int n) { return mp_asm_base_get_cur_to_write_bytes(&as->base, n); } @@ -51,7 +62,7 @@ void asm_thumb_end_pass(asm_thumb_t *as) { (void)as; // could check labels are resolved... - #if defined(MCU_SERIES_F7) + #if defined(__ICACHE_PRESENT) && __ICACHE_PRESENT == 1 if (as->base.pass == MP_ASM_PASS_EMIT) { // flush D-cache, so the code emitted is stored in memory MP_HAL_CLEAN_DCACHE(as->base.code_base, as->base.code_size); @@ -89,6 +100,7 @@ STATIC void asm_thumb_write_word32(asm_thumb_t *as, int w32) { #define OP_POP_RLIST(rlolist) (0xbc00 | (rlolist)) #define OP_POP_RLIST_PC(rlolist) (0xbc00 | 0x0100 | (rlolist)) +// The number of words must fit in 7 unsigned bits #define OP_ADD_SP(num_words) (0xb000 | (num_words)) #define OP_SUB_SP(num_words) (0xb080 | (num_words)) @@ -142,7 +154,11 @@ void asm_thumb_entry(asm_thumb_t *as, int num_locals) { } asm_thumb_op16(as, OP_PUSH_RLIST_LR(reglist)); if (stack_adjust > 0) { - asm_thumb_op16(as, OP_SUB_SP(stack_adjust)); + if (UNSIGNED_FIT7(stack_adjust)) { + asm_thumb_op16(as, OP_SUB_SP(stack_adjust)); + } else { + asm_thumb_op32(as, OP_SUB_W_RRI_HI(ASM_THUMB_REG_SP), OP_SUB_W_RRI_LO(ASM_THUMB_REG_SP, stack_adjust * 4)); + } } as->push_reglist = reglist; as->stack_adjust = stack_adjust; @@ -150,7 +166,11 @@ void asm_thumb_entry(asm_thumb_t *as, int num_locals) { void asm_thumb_exit(asm_thumb_t *as) { if (as->stack_adjust > 0) { - asm_thumb_op16(as, OP_ADD_SP(as->stack_adjust)); + if (UNSIGNED_FIT7(as->stack_adjust)) { + asm_thumb_op16(as, OP_ADD_SP(as->stack_adjust)); + } else { + asm_thumb_op32(as, OP_ADD_W_RRI_HI(ASM_THUMB_REG_SP), OP_ADD_W_RRI_LO(ASM_THUMB_REG_SP, as->stack_adjust * 4)); + } } asm_thumb_op16(as, OP_POP_RLIST_PC(as->push_reglist)); } @@ -269,21 +289,6 @@ void asm_thumb_mov_reg_i32_optimised(asm_thumb_t *as, uint reg_dest, int i32) { } } -// i32 is stored as a full word in the code, and aligned to machine-word boundary -// TODO this is very inefficient, improve it! -void asm_thumb_mov_reg_i32_aligned(asm_thumb_t *as, uint reg_dest, int i32) { - // align on machine-word + 2 - if ((as->base.code_offset & 3) == 0) { - asm_thumb_op16(as, ASM_THUMB_OP_NOP); - } - // jump over the i32 value (instruction prefetch adds 2 to PC) - asm_thumb_op16(as, OP_B_N(2)); - // store i32 on machine-word aligned boundary - mp_asm_base_data(&as->base, 4, i32); - // do the actual load of the i32 value - asm_thumb_mov_reg_i32_optimised(as, reg_dest, i32); -} - #define OP_STR_TO_SP_OFFSET(rlo_dest, word_offset) (0x9000 | ((rlo_dest) << 8) | ((word_offset) & 0x00ff)) #define OP_LDR_FROM_SP_OFFSET(rlo_dest, word_offset) (0x9800 | ((rlo_dest) << 8) | ((word_offset) & 0x00ff)) @@ -310,6 +315,27 @@ void asm_thumb_mov_reg_local_addr(asm_thumb_t *as, uint rlo_dest, int local_num) asm_thumb_op16(as, OP_ADD_REG_SP_OFFSET(rlo_dest, word_offset)); } +void asm_thumb_mov_reg_pcrel(asm_thumb_t *as, uint rlo_dest, uint label) { + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - as->base.code_offset; + rel -= 4 + 4; // adjust for mov_reg_i16 and then PC+4 prefetch of add_reg_reg + rel |= 1; // to stay in Thumb state when jumping to this address + asm_thumb_mov_reg_i16(as, ASM_THUMB_OP_MOVW, rlo_dest, rel); // 4 bytes + asm_thumb_add_reg_reg(as, rlo_dest, ASM_THUMB_REG_R15); // 2 bytes +} + +static inline void asm_thumb_ldr_reg_reg_i12(asm_thumb_t *as, uint reg_dest, uint reg_base, uint word_offset) { + asm_thumb_op32(as, OP_LDR_W_HI(reg_base), OP_LDR_W_LO(reg_dest, word_offset * 4)); +} + +void asm_thumb_ldr_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint word_offset) { + if (reg_dest < ASM_THUMB_REG_R8 && reg_base < ASM_THUMB_REG_R8 && UNSIGNED_FIT5(word_offset)) { + asm_thumb_ldr_rlo_rlo_i5(as, reg_dest, reg_base, word_offset); + } else { + asm_thumb_ldr_reg_reg_i12(as, reg_dest, reg_base, word_offset); + } +} + // this could be wrong, because it should have a range of +/- 16MiB... #define OP_BW_HI(byte_offset) (0xf000 | (((byte_offset) >> 12) & 0x07ff)) #define OP_BW_LO(byte_offset) (0xb800 | (((byte_offset) >> 1) & 0x07ff)) @@ -328,7 +354,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 +373,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)); } } @@ -355,25 +381,10 @@ void asm_thumb_bcc_label(asm_thumb_t *as, int cond, uint label) { #define OP_BLX(reg) (0x4780 | ((reg) << 3)) #define OP_SVC(arg) (0xdf00 | (arg)) -void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp) { - /* TODO make this use less bytes - uint rlo_base = ASM_THUMB_REG_R3; - uint rlo_dest = ASM_THUMB_REG_R7; - uint word_offset = 4; - asm_thumb_op16(as, 0x0000); - asm_thumb_op16(as, 0x6800 | (word_offset << 6) | (rlo_base << 3) | rlo_dest); // ldr rlo_dest, [rlo_base, #offset] - asm_thumb_op16(as, 0x4780 | (ASM_THUMB_REG_R9 << 3)); // blx reg - */ - - if (fun_id < 32) { - // load ptr to function from table, indexed by fun_id (must be in range 0-31); 4 bytes - asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, reg_temp, ASM_THUMB_REG_R7, fun_id)); - asm_thumb_op16(as, OP_BLX(reg_temp)); - } else { - // load ptr to function into register using immediate; 6 bytes - asm_thumb_mov_reg_i32(as, reg_temp, (mp_uint_t)fun_ptr); - asm_thumb_op16(as, OP_BLX(reg_temp)); - } +void asm_thumb_bl_ind(asm_thumb_t *as, uint fun_id, uint reg_temp) { + // Load ptr to function from table, indexed by fun_id, then call it + asm_thumb_ldr_reg_reg_i12_optimised(as, reg_temp, ASM_THUMB_REG_FUN_TABLE, fun_id); + asm_thumb_op16(as, OP_BLX(reg_temp)); } #endif // MICROPY_EMIT_THUMB || MICROPY_EMIT_INLINE_THUMB diff --git a/py/asmthumb.h b/py/asmthumb.h index 32219eb55ac7a..b4828b125d691 100644 --- a/py/asmthumb.h +++ b/py/asmthumb.h @@ -46,6 +46,7 @@ #define ASM_THUMB_REG_R13 (13) #define ASM_THUMB_REG_R14 (14) #define ASM_THUMB_REG_R15 (15) +#define ASM_THUMB_REG_SP (ASM_THUMB_REG_R13) #define ASM_THUMB_REG_LR (REG_R14) #define ASM_THUMB_CC_EQ (0x0) @@ -94,8 +95,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 +130,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 +158,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 +192,29 @@ 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 5: hi register operations (add, cmp, mov, bx) +// For add/cmp/mov, at least one of the args must be a high register + +#define ASM_THUMB_FORMAT_5_ADD (0x4400) +#define ASM_THUMB_FORMAT_5_BX (0x4700) + +#define ASM_THUMB_FORMAT_5_ENCODE(op, r_dest, r_src) \ + ((op) | ((r_dest) << 4 & 0x0080) | ((r_src) << 3) | ((r_dest) & 0x0007)) + +static inline void asm_thumb_format_5(asm_thumb_t *as, uint op, uint r_dest, uint r_src) { + asm_thumb_op16(as, ASM_THUMB_FORMAT_5_ENCODE(op, r_dest, r_src)); +} + +static inline void asm_thumb_add_reg_reg(asm_thumb_t *as, uint r_dest, uint r_src) { + asm_thumb_format_5(as, ASM_THUMB_FORMAT_5_ADD, r_dest, r_src); +} +static inline void asm_thumb_bx_reg(asm_thumb_t *as, uint r_src) { + asm_thumb_format_5(as, ASM_THUMB_FORMAT_5_BX, 0, r_src); +} // FORMAT 9: load/store with immediate offset // For word transfers the offset must be aligned, and >>2 @@ -198,21 +234,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_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_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); +} // TODO convert these to above format style @@ -229,14 +272,19 @@ bool asm_thumb_bl_label(asm_thumb_t *as, uint label); void asm_thumb_mov_reg_i32(asm_thumb_t *as, uint reg_dest, mp_uint_t i32_src); // convenience void asm_thumb_mov_reg_i32_optimised(asm_thumb_t *as, uint reg_dest, int i32_src); // convenience -void asm_thumb_mov_reg_i32_aligned(asm_thumb_t *as, uint reg_dest, int i32); // convenience void asm_thumb_mov_local_reg(asm_thumb_t *as, int local_num_dest, uint rlo_src); // convenience void asm_thumb_mov_reg_local(asm_thumb_t *as, uint rlo_dest, int local_num); // convenience void asm_thumb_mov_reg_local_addr(asm_thumb_t *as, uint rlo_dest, int local_num); // convenience +void asm_thumb_mov_reg_pcrel(asm_thumb_t *as, uint rlo_dest, uint label); + +void asm_thumb_ldr_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint byte_offset); // convenience void asm_thumb_b_label(asm_thumb_t *as, uint label); // convenience: picks narrow or wide branch void asm_thumb_bcc_label(asm_thumb_t *as, int cc, uint label); // convenience: picks narrow or wide branch -void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp); // convenience +void asm_thumb_bl_ind(asm_thumb_t *as, uint fun_id, uint reg_temp); // convenience + +// Holds a pointer to mp_fun_table +#define ASM_THUMB_REG_FUN_TABLE ASM_THUMB_REG_R7 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -261,18 +309,20 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp #define REG_LOCAL_3 ASM_THUMB_REG_R6 #define REG_LOCAL_NUM (3) +#define REG_FUN_TABLE ASM_THUMB_REG_FUN_TABLE + #define ASM_T asm_thumb_t #define ASM_END_PASS asm_thumb_end_pass #define ASM_ENTRY asm_thumb_entry #define ASM_EXIT asm_thumb_exit #define ASM_JUMP asm_thumb_b_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_thumb_cmp_rlo_i8(as, reg, 0); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_EQ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ asm_thumb_cmp_rlo_i8(as, reg, 0); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_NE, label); \ @@ -282,14 +332,15 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp asm_thumb_cmp_rlo_rlo(as, reg1, reg2); \ asm_thumb_bcc_label(as, ASM_THUMB_CC_EQ, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_thumb_bl_ind(as, ptr, idx, ASM_THUMB_REG_R3) +#define ASM_JUMP_REG(as, reg) asm_thumb_bx_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_thumb_bl_ind(as, idx, ASM_THUMB_REG_R3) #define ASM_MOV_LOCAL_REG(as, local_num, reg) asm_thumb_mov_local_reg((as), (local_num), (reg)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_thumb_mov_reg_i32_optimised((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_thumb_mov_reg_i32_aligned((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_thumb_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_thumb_mov_reg_reg((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_thumb_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, rlo_dest, label) asm_thumb_mov_reg_pcrel((as), (rlo_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_LSL, (reg_dest), (reg_shift)) #define ASM_ASR_REG_REG(as, reg_dest, reg_shift) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_ASR, (reg_dest), (reg_shift)) @@ -301,7 +352,7 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_thumb_format_4((as), ASM_THUMB_FORMAT_4_MUL, (reg_dest), (reg_src)) #define ASM_LOAD_REG_REG(as, reg_dest, reg_base) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) -#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), (word_offset)) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_thumb_ldr_reg_reg_i12_optimised((as), (reg_dest), (reg_base), (word_offset)) #define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) asm_thumb_ldrb_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) #define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) asm_thumb_ldrh_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) #define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) diff --git a/py/asmx64.c b/py/asmx64.c index 8706b806e5171..b881491121ed7 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -63,18 +63,20 @@ #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_TEST_R64_WITH_RM64 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) +#define OPCODE_JMP_RM64 (0xff) /* /4 */ #define OPCODE_JCC_REL8 (0x70) /* | jcc type */ #define OPCODE_JCC_REL32_A (0x0f) #define OPCODE_JCC_REL32_B (0x80) /* | jcc type */ @@ -121,14 +123,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 +138,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 +147,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 +157,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); @@ -181,21 +183,22 @@ STATIC void asm_x64_write_word32_to(asm_x64_t *as, int offset, int w32) { */ STATIC void asm_x64_write_r64_disp(asm_x64_t *as, int r64, int disp_r64, int disp_offset) { - assert(disp_r64 != ASM_X64_REG_RSP); - - if (disp_r64 == ASM_X64_REG_R12) { - // special case for r12; not fully implemented - assert(SIGNED_FIT8(disp_offset)); - asm_x64_write_byte_3(as, MODRM_R64(r64) | MODRM_RM_DISP8 | MODRM_RM_R64(disp_r64), 0x24, IMM32_L0(disp_offset)); - return; - } - - if (disp_offset == 0 && disp_r64 != ASM_X64_REG_RBP) { - asm_x64_write_byte_1(as, MODRM_R64(r64) | MODRM_RM_DISP0 | MODRM_RM_R64(disp_r64)); + uint8_t rm_disp; + if (disp_offset == 0 && (disp_r64 & 7) != ASM_X64_REG_RBP) { + rm_disp = MODRM_RM_DISP0; } else if (SIGNED_FIT8(disp_offset)) { - asm_x64_write_byte_2(as, MODRM_R64(r64) | MODRM_RM_DISP8 | MODRM_RM_R64(disp_r64), IMM32_L0(disp_offset)); + rm_disp = MODRM_RM_DISP8; } else { - asm_x64_write_byte_1(as, MODRM_R64(r64) | MODRM_RM_DISP32 | MODRM_RM_R64(disp_r64)); + rm_disp = MODRM_RM_DISP32; + } + asm_x64_write_byte_1(as, MODRM_R64(r64) | rm_disp | MODRM_RM_R64(disp_r64)); + if ((disp_r64 & 7) == ASM_X64_REG_RSP) { + // Special case for rsp and r12, they need a SIB byte + asm_x64_write_byte_1(as, 0x24); + } + if (rm_disp == MODRM_RM_DISP8) { + asm_x64_write_byte_1(as, IMM32_L0(disp_offset)); + } else if (rm_disp == MODRM_RM_DISP32) { asm_x64_write_word32(as, disp_offset); } } @@ -361,15 +364,6 @@ void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r } } -// src_i64 is stored as a full word in the code, and aligned to machine-word boundary -void asm_x64_mov_i64_to_r64_aligned(asm_x64_t *as, int64_t src_i64, int dest_r64) { - // mov instruction uses 2 bytes for the instruction, before the i64 - while (((as->base.code_offset + 2) & (WORD_SIZE - 1)) != 0) { - asm_x64_nop(as); - } - asm_x64_mov_i64_to_r64(as, src_i64, dest_r64); -} - void asm_x64_and_r64_r64(asm_x64_t *as, int dest_r64, int src_r64) { asm_x64_generic_r64_r64(as, dest_r64, src_r64, OPCODE_AND_R64_TO_RM64); } @@ -382,11 +376,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); } @@ -465,17 +459,25 @@ void asm_x64_cmp_i32_with_r32(asm_x64_t *as, int src_i32, int src_r32) { */ void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b) { - // TODO implement for other registers - assert(src_r64_a == ASM_X64_REG_RAX); - assert(src_r64_b == ASM_X64_REG_RAX); + assert(src_r64_a < 8); + assert(src_r64_b < 8); asm_x64_write_byte_2(as, OPCODE_TEST_R8_WITH_RM8, MODRM_R64(src_r64_a) | MODRM_RM_REG | MODRM_RM_R64(src_r64_b)); } +void asm_x64_test_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b) { + asm_x64_generic_r64_r64(as, src_r64_b, src_r64_a, OPCODE_TEST_R64_WITH_RM64); +} + void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8) { assert(dest_r8 < 8); asm_x64_write_byte_3(as, OPCODE_SETCC_RM8_A, OPCODE_SETCC_RM8_B | jcc_type, MODRM_R64(0) | MODRM_RM_REG | MODRM_RM_R64(dest_r8)); } +void asm_x64_jmp_reg(asm_x64_t *as, int src_r64) { + assert(src_r64 < 8); + asm_x64_write_byte_2(as, OPCODE_JMP_RM64, MODRM_R64(4) | MODRM_RM_REG | MODRM_RM_R64(src_r64)); +} + STATIC mp_uint_t get_label_dest(asm_x64_t *as, mp_uint_t label) { assert(label < as->base.max_num_labels); return as->base.label_offsets[label]; @@ -496,7 +498,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 +520,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); @@ -528,63 +530,72 @@ 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) { assert(num_locals >= 0); asm_x64_push_r64(as, ASM_X64_REG_RBP); - asm_x64_mov_r64_r64(as, ASM_X64_REG_RBP, ASM_X64_REG_RSP); - num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary - asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, num_locals * WORD_SIZE); asm_x64_push_r64(as, ASM_X64_REG_RBX); asm_x64_push_r64(as, ASM_X64_REG_R12); asm_x64_push_r64(as, ASM_X64_REG_R13); + num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary + asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, num_locals * WORD_SIZE); as->num_locals = num_locals; } void asm_x64_exit(asm_x64_t *as) { + asm_x64_sub_r64_i32(as, ASM_X64_REG_RSP, -as->num_locals * WORD_SIZE); asm_x64_pop_r64(as, ASM_X64_REG_R13); asm_x64_pop_r64(as, ASM_X64_REG_R12); asm_x64_pop_r64(as, ASM_X64_REG_RBX); - asm_x64_write_byte_1(as, OPCODE_LEAVE); + asm_x64_pop_r64(as, ASM_X64_REG_RBP); asm_x64_ret(as); } // locals: // - stored on the stack in ascending order // - numbered 0 through as->num_locals-1 -// - RBP points above the last local +// - RSP points to the first local // -// | RBP -// v +// | RSP +// v // l0 l1 l2 ... l(n-1) // ^ ^ // | low address | high address in RAM // -STATIC int asm_x64_local_offset_from_ebp(asm_x64_t *as, int local_num) { - return (-as->num_locals + local_num) * WORD_SIZE; +STATIC int asm_x64_local_offset_from_rsp(asm_x64_t *as, int local_num) { + (void)as; + // Stack is full descending, RSP points to local0 + return local_num * WORD_SIZE; } void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64) { - asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, src_local_num), dest_r64); + asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, src_local_num), dest_r64); } void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num) { - asm_x64_mov_r64_to_mem64(as, src_r64, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, dest_local_num)); + asm_x64_mov_r64_to_mem64(as, src_r64, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, dest_local_num)); } void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64) { - int offset = asm_x64_local_offset_from_ebp(as, local_num); + int offset = asm_x64_local_offset_from_rsp(as, local_num); if (offset == 0) { - asm_x64_mov_r64_r64(as, dest_r64, ASM_X64_REG_RBP); + asm_x64_mov_r64_r64(as, dest_r64, ASM_X64_REG_RSP); } else { - asm_x64_lea_disp_to_r64(as, ASM_X64_REG_RBP, offset, dest_r64); + asm_x64_lea_disp_to_r64(as, ASM_X64_REG_RSP, offset, dest_r64); } } +void asm_x64_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label) { + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - (as->base.code_offset + 7); + asm_x64_write_byte_3(as, REX_PREFIX | REX_W | REX_R_FROM_R64(dest_r64), OPCODE_LEA_MEM_TO_R64, MODRM_R64(dest_r64) | MODRM_RM_R64(5)); + asm_x64_write_word32(as, rel); +} + /* void asm_x64_push_local(asm_x64_t *as, int local_num) { - asm_x64_push_disp(as, ASM_X64_REG_RBP, asm_x64_local_offset_from_ebp(as, local_num)); + asm_x64_push_disp(as, ASM_X64_REG_RSP, asm_x64_local_offset_from_rsp(as, local_num)); } void asm_x64_push_local_addr(asm_x64_t *as, int local_num, int temp_r64) { - asm_x64_mov_r64_r64(as, temp_r64, ASM_X64_REG_RBP); - asm_x64_add_i32_to_r32(as, asm_x64_local_offset_from_ebp(as, local_num), temp_r64); + asm_x64_mov_r64_r64(as, temp_r64, ASM_X64_REG_RSP); + asm_x64_add_i32_to_r32(as, asm_x64_local_offset_from_rsp(as, local_num), temp_r64); asm_x64_push_r64(as, temp_r64); } */ @@ -610,21 +621,10 @@ 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) { +void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r64) { assert(temp_r64 < 8); -#ifdef __LP64__ - asm_x64_mov_i64_to_r64_optimised(as, (int64_t)ptr, temp_r64); -#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 + asm_x64_mov_mem64_to_r64(as, ASM_X64_REG_FUN_TABLE, fun_id * WORD_SIZE, temp_r64); 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 - /* - asm_x64_write_byte_1(as, OPCODE_CALL_REL32); - asm_x64_write_word32(as, ptr - (void*)(as->code_base + as->code_offset + 4)); - */ } #endif // MICROPY_EMIT_X64 diff --git a/py/asmx64.h b/py/asmx64.h index 113d925119916..ceea426d7427c 100644 --- a/py/asmx64.h +++ b/py/asmx64.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -79,13 +79,12 @@ 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); void asm_x64_mov_r16_to_mem16(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); void asm_x64_mov_r32_to_mem32(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); @@ -97,22 +96,28 @@ 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_test_r64_with_r64(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_reg(asm_x64_t *as, int src_r64); +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_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label); +void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r32); + +// Holds a pointer to mp_fun_table +#define ASM_X64_REG_FUN_TABLE ASM_X64_REG_RBP #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -139,20 +144,31 @@ void asm_x64_call_ind(asm_x64_t* as, void* ptr, int temp_r32); #define REG_LOCAL_3 ASM_X64_REG_R13 #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_X64_REG_FUN_TABLE + #define ASM_T asm_x64_t #define ASM_END_PASS asm_x64_end_pass #define ASM_ENTRY asm_x64_entry #define ASM_EXIT asm_x64_exit #define ASM_JUMP asm_x64_jmp_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ - asm_x64_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x64_test_r8_with_r8((as), (reg), (reg)); \ + } else { \ + asm_x64_test_r64_with_r64((as), (reg), (reg)); \ + } \ asm_x64_jcc_label(as, ASM_X64_CC_JZ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ - asm_x64_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x64_test_r8_with_r8((as), (reg), (reg)); \ + } else { \ + asm_x64_test_r64_with_r64((as), (reg), (reg)); \ + } \ asm_x64_jcc_label(as, ASM_X64_CC_JNZ, label); \ } while (0) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ @@ -160,14 +176,15 @@ void asm_x64_call_ind(asm_x64_t* as, void* ptr, int temp_r32); asm_x64_cmp_r64_with_r64(as, reg1, reg2); \ asm_x64_jcc_label(as, ASM_X64_CC_JE, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_x64_call_ind(as, ptr, ASM_X64_REG_RAX) +#define ASM_JUMP_REG(as, reg) asm_x64_jmp_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_x64_call_ind(as, idx, ASM_X64_REG_RAX) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_x64_mov_r64_to_local((as), (reg_src), (local_num)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_x64_mov_i64_to_r64_optimised((as), (imm), (reg_dest)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_x64_mov_i64_to_r64_aligned((as), (imm), (reg_dest)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_x64_mov_local_to_r64((as), (local_num), (reg_dest)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_x64_mov_r64_r64((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_x64_mov_local_addr_to_r64((as), (local_num), (reg_dest)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_x64_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG(as, reg) asm_x64_shl_r64_cl((as), (reg)) #define ASM_ASR_REG(as, reg) asm_x64_sar_r64_cl((as), (reg)) diff --git a/py/asmx86.c b/py/asmx86.c index 8a08c68a039b9..b238321bda3c3 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,18 +63,20 @@ #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_TEST_R32_WITH_RM32 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) +#define OPCODE_JMP_RM32 (0xff) /* /4 */ #define OPCODE_JCC_REL8 (0x70) /* | jcc type */ #define OPCODE_JCC_REL32_A (0x0f) #define OPCODE_JCC_REL32_B (0x80) /* | jcc type */ @@ -101,14 +103,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 +118,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 +127,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); @@ -135,14 +137,22 @@ STATIC void asm_x86_write_word32(asm_x86_t *as, int w32) { } STATIC void asm_x86_write_r32_disp(asm_x86_t *as, int r32, int disp_r32, int disp_offset) { - assert(disp_r32 != ASM_X86_REG_ESP); - + uint8_t rm_disp; if (disp_offset == 0 && disp_r32 != ASM_X86_REG_EBP) { - asm_x86_write_byte_1(as, MODRM_R32(r32) | MODRM_RM_DISP0 | MODRM_RM_R32(disp_r32)); + rm_disp = MODRM_RM_DISP0; } else if (SIGNED_FIT8(disp_offset)) { - asm_x86_write_byte_2(as, MODRM_R32(r32) | MODRM_RM_DISP8 | MODRM_RM_R32(disp_r32), IMM32_L0(disp_offset)); + rm_disp = MODRM_RM_DISP8; } else { - asm_x86_write_byte_1(as, MODRM_R32(r32) | MODRM_RM_DISP32 | MODRM_RM_R32(disp_r32)); + rm_disp = MODRM_RM_DISP32; + } + asm_x86_write_byte_1(as, MODRM_R32(r32) | rm_disp | MODRM_RM_R32(disp_r32)); + if (disp_r32 == ASM_X86_REG_ESP) { + // Special case for esp, it needs a SIB byte + asm_x86_write_byte_1(as, 0x24); + } + if (rm_disp == MODRM_RM_DISP8) { + asm_x86_write_byte_1(as, IMM32_L0(disp_offset)); + } else if (rm_disp == MODRM_RM_DISP32) { asm_x86_write_word32(as, disp_offset); } } @@ -151,9 +161,11 @@ STATIC void asm_x86_generic_r32_r32(asm_x86_t *as, int dest_r32, int src_r32, in asm_x86_write_byte_2(as, op, MODRM_R32(src_r32) | MODRM_RM_REG | MODRM_RM_R32(dest_r32)); } +#if 0 STATIC void asm_x86_nop(asm_x86_t *as) { asm_x86_write_byte_1(as, OPCODE_NOP); } +#endif STATIC void asm_x86_push_r32(asm_x86_t *as, int src_r32) { asm_x86_write_byte_1(as, OPCODE_PUSH_R32 | src_r32); @@ -229,15 +241,6 @@ void asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32) { asm_x86_write_word32(as, src_i32); } -// src_i32 is stored as a full word in the code, and aligned to machine-word boundary -void asm_x86_mov_i32_to_r32_aligned(asm_x86_t *as, int32_t src_i32, int dest_r32) { - // mov instruction uses 1 byte for the instruction, before the i32 - while (((as->base.code_offset + 1) & (WORD_SIZE - 1)) != 0) { - asm_x86_nop(as); - } - asm_x86_mov_i32_to_r32(as, src_i32, dest_r32); -} - void asm_x86_and_r32_r32(asm_x86_t *as, int dest_r32, int src_r32) { asm_x86_generic_r32_r32(as, dest_r32, src_r32, OPCODE_AND_R32_TO_RM32); } @@ -250,11 +253,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); } @@ -312,7 +315,7 @@ void asm_x86_sar_r32_by_imm(asm_x86_t *as, int r32, int imm) { #endif void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b) { - asm_x86_write_byte_2(as, OPCODE_CMP_R32_WITH_RM32, MODRM_R32(src_r32_a) | MODRM_RM_REG | MODRM_RM_R32(src_r32_b)); + asm_x86_generic_r32_r32(as, src_r32_b, src_r32_a, OPCODE_CMP_R32_WITH_RM32); } #if 0 @@ -328,16 +331,21 @@ void asm_x86_cmp_i32_with_r32(asm_x86_t *as, int src_i32, int src_r32) { #endif void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b) { - // TODO implement for other registers - assert(src_r32_a == ASM_X86_REG_EAX); - assert(src_r32_b == ASM_X86_REG_EAX); asm_x86_write_byte_2(as, OPCODE_TEST_R8_WITH_RM8, MODRM_R32(src_r32_a) | MODRM_RM_REG | MODRM_RM_R32(src_r32_b)); } +void asm_x86_test_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b) { + asm_x86_generic_r32_r32(as, src_r32_b, src_r32_a, OPCODE_TEST_R32_WITH_RM32); +} + void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8) { asm_x86_write_byte_3(as, OPCODE_SETCC_RM8_A, OPCODE_SETCC_RM8_B | jcc_type, MODRM_R32(0) | MODRM_RM_REG | MODRM_RM_R32(dest_r8)); } +void asm_x86_jmp_reg(asm_x86_t *as, int src_r32) { + asm_x86_write_byte_2(as, OPCODE_JMP_RM32, MODRM_R32(4) | MODRM_RM_REG | MODRM_RM_R32(src_r32)); +} + STATIC mp_uint_t get_label_dest(asm_x86_t *as, mp_uint_t label) { assert(label < as->base.max_num_labels); return as->base.label_offsets[label]; @@ -358,7 +366,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 +388,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); @@ -390,87 +398,102 @@ 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) { assert(num_locals >= 0); asm_x86_push_r32(as, ASM_X86_REG_EBP); - asm_x86_mov_r32_r32(as, ASM_X86_REG_EBP, ASM_X86_REG_ESP); - if (num_locals > 0) { - asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, num_locals * WORD_SIZE); - } asm_x86_push_r32(as, ASM_X86_REG_EBX); asm_x86_push_r32(as, ASM_X86_REG_ESI); asm_x86_push_r32(as, ASM_X86_REG_EDI); - // TODO align stack on 16-byte boundary + num_locals |= 1; // make it odd so stack is aligned on 16 byte boundary + asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, num_locals * WORD_SIZE); as->num_locals = num_locals; } void asm_x86_exit(asm_x86_t *as) { + asm_x86_sub_r32_i32(as, ASM_X86_REG_ESP, -as->num_locals * WORD_SIZE); asm_x86_pop_r32(as, ASM_X86_REG_EDI); asm_x86_pop_r32(as, ASM_X86_REG_ESI); asm_x86_pop_r32(as, ASM_X86_REG_EBX); - asm_x86_write_byte_1(as, OPCODE_LEAVE); + asm_x86_pop_r32(as, ASM_X86_REG_EBP); asm_x86_ret(as); } +STATIC int asm_x86_arg_offset_from_esp(asm_x86_t *as, size_t arg_num) { + // Above esp are: locals, 4 saved registers, return eip, arguments + return (as->num_locals + 4 + 1 + arg_num) * WORD_SIZE; +} + #if 0 void asm_x86_push_arg(asm_x86_t *as, int src_arg_num) { - asm_x86_push_disp(as, ASM_X86_REG_EBP, 2 * WORD_SIZE + src_arg_num * WORD_SIZE); + asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, src_arg_num)); } #endif void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32) { - asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_EBP, 2 * WORD_SIZE + src_arg_num * WORD_SIZE, dest_r32); + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, src_arg_num), dest_r32); } #if 0 void asm_x86_mov_r32_to_arg(asm_x86_t *as, int src_r32, int dest_arg_num) { - asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_EBP, 2 * WORD_SIZE + dest_arg_num * WORD_SIZE); + asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_ESP, asm_x86_arg_offset_from_esp(as, dest_arg_num)); } #endif // locals: // - stored on the stack in ascending order // - numbered 0 through as->num_locals-1 -// - EBP points above the last local +// - ESP points to the first local // -// | EBP -// v +// | ESP +// v // l0 l1 l2 ... l(n-1) // ^ ^ // | low address | high address in RAM // -STATIC int asm_x86_local_offset_from_ebp(asm_x86_t *as, int local_num) { - return (-as->num_locals + local_num) * WORD_SIZE; +STATIC int asm_x86_local_offset_from_esp(asm_x86_t *as, int local_num) { + (void)as; + // Stack is full descending, ESP points to local0 + return local_num * WORD_SIZE; } void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32) { - asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, src_local_num), dest_r32); + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, src_local_num), dest_r32); } void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num) { - asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, dest_local_num)); + asm_x86_mov_r32_to_mem32(as, src_r32, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, dest_local_num)); } void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32) { - int offset = asm_x86_local_offset_from_ebp(as, local_num); + int offset = asm_x86_local_offset_from_esp(as, local_num); if (offset == 0) { - asm_x86_mov_r32_r32(as, dest_r32, ASM_X86_REG_EBP); + asm_x86_mov_r32_r32(as, dest_r32, ASM_X86_REG_ESP); } else { - asm_x86_lea_disp_to_r32(as, ASM_X86_REG_EBP, offset, dest_r32); + asm_x86_lea_disp_to_r32(as, ASM_X86_REG_ESP, offset, dest_r32); } } +void asm_x86_mov_reg_pcrel(asm_x86_t *as, int dest_r32, mp_uint_t label) { + asm_x86_write_byte_1(as, OPCODE_CALL_REL32); + asm_x86_write_word32(as, 0); + mp_uint_t dest = get_label_dest(as, label); + mp_int_t rel = dest - as->base.code_offset; + asm_x86_pop_r32(as, dest_r32); + // PC rel is usually a forward reference, so need to assume it's large + asm_x86_write_byte_2(as, OPCODE_ADD_I32_TO_RM32, MODRM_R32(0) | MODRM_RM_REG | MODRM_RM_R32(dest_r32)); + asm_x86_write_word32(as, rel); +} + #if 0 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)); + asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, local_num)); } -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); +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_ESP); + asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_esp(as, local_num), temp_r32); asm_x86_push_r32(as, temp_r32); } #endif -void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32) { +void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32) { // TODO align stack on 16-byte boundary before the call assert(n_args <= 5); if (n_args > 4) { @@ -488,20 +511,10 @@ 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__ - // 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 - // If we get here, sizeof(int) == sizeof(void*). - asm_x86_mov_i32_to_r32(as, (int32_t)ptr, temp_r32); -#endif + + // Load the pointer to the function and make the call + asm_x86_mov_mem32_to_r32(as, ASM_X86_REG_FUN_TABLE, fun_id * WORD_SIZE, temp_r32); 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 - /* - asm_x86_write_byte_1(as, OPCODE_CALL_REL32); - asm_x86_write_word32(as, ptr - (void*)(as->code_base + as->base.code_offset + 4)); - */ // the caller must clean up the stack if (n_args > 0) { diff --git a/py/asmx86.h b/py/asmx86.h index 05902350fc8d2..930350d11bef8 100644 --- a/py/asmx86.h +++ b/py/asmx86.h @@ -82,9 +82,8 @@ 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); void asm_x86_mov_r16_to_mem16(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); void asm_x86_mov_r32_to_mem32(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); @@ -94,23 +93,29 @@ 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_test_r32_with_r32(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_reg(asm_x86_t *as, int src_r86); +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_mov_reg_pcrel(asm_x86_t *as, int dest_r64, mp_uint_t label); +void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32); + +// Holds a pointer to mp_fun_table +#define ASM_X86_REG_FUN_TABLE ASM_X86_REG_EBP #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -137,20 +142,31 @@ void asm_x86_call_ind(asm_x86_t* as, void* ptr, mp_uint_t n_args, int temp_r32); #define REG_LOCAL_3 ASM_X86_REG_EDI #define REG_LOCAL_NUM (3) +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_X86_REG_FUN_TABLE + #define ASM_T asm_x86_t #define ASM_END_PASS asm_x86_end_pass #define ASM_ENTRY asm_x86_entry #define ASM_EXIT asm_x86_exit #define ASM_JUMP asm_x86_jmp_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ - asm_x86_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x86_test_r8_with_r8(as, reg, reg); \ + } else { \ + asm_x86_test_r32_with_r32(as, reg, reg); \ + } \ asm_x86_jcc_label(as, ASM_X86_CC_JZ, label); \ } while (0) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ do { \ - asm_x86_test_r8_with_r8(as, reg, reg); \ + if (bool_test) { \ + asm_x86_test_r8_with_r8(as, reg, reg); \ + } else { \ + asm_x86_test_r32_with_r32(as, reg, reg); \ + } \ asm_x86_jcc_label(as, ASM_X86_CC_JNZ, label); \ } while (0) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ @@ -158,14 +174,15 @@ void asm_x86_call_ind(asm_x86_t* as, void* ptr, mp_uint_t n_args, int temp_r32); asm_x86_cmp_r32_with_r32(as, reg1, reg2); \ asm_x86_jcc_label(as, ASM_X86_CC_JE, label); \ } while (0) -#define ASM_CALL_IND(as, ptr, idx) asm_x86_call_ind(as, ptr, mp_f_n_args[idx], ASM_X86_REG_EAX) +#define ASM_JUMP_REG(as, reg) asm_x86_jmp_reg((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_x86_call_ind(as, idx, mp_f_n_args[idx], ASM_X86_REG_EAX) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_x86_mov_r32_to_local((as), (reg_src), (local_num)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_x86_mov_i32_to_r32((as), (imm), (reg_dest)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_x86_mov_i32_to_r32_aligned((as), (imm), (reg_dest)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_x86_mov_local_to_r32((as), (local_num), (reg_dest)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_x86_mov_r32_r32((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_x86_mov_local_addr_to_r32((as), (local_num), (reg_dest)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_x86_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG(as, reg) asm_x86_shl_r32_cl((as), (reg)) #define ASM_ASR_REG(as, reg) asm_x86_sar_r32_cl((as), (reg)) diff --git a/py/asmxtensa.c b/py/asmxtensa.c index 98b49ecb5e1a8..a8e3a2655c9bc 100644 --- a/py/asmxtensa.c +++ b/py/asmxtensa.c @@ -37,6 +37,7 @@ #define WORD_SIZE (4) #define SIGNED_FIT8(x) ((((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80)) #define SIGNED_FIT12(x) ((((x) & 0xfffff800) == 0) || (((x) & 0xfffff800) == 0xfffff800)) +#define NUM_REGS_SAVED (5) void asm_xtensa_end_pass(asm_xtensa_t *as) { as->num_const = as->cur_const; @@ -65,28 +66,39 @@ 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; - asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, -as->stack_adjust); + // adjust the stack-pointer to store a0, a12, a13, a14, a15 and locals, 16-byte aligned + as->stack_adjust = (((NUM_REGS_SAVED + num_locals) * WORD_SIZE) + 15) & ~15; + if (SIGNED_FIT8(-as->stack_adjust)) { + asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, -as->stack_adjust); + } else { + asm_xtensa_op_movi(as, ASM_XTENSA_REG_A9, as->stack_adjust); + asm_xtensa_op_sub(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A9); + } - // save return value (a0) and callee-save registers (a12, a13, a14) + // save return value (a0) and callee-save registers (a12, a13, a14, a15) asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_A1, 0); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A12, ASM_XTENSA_REG_A1, 1); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A13, ASM_XTENSA_REG_A1, 2); - asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A14, ASM_XTENSA_REG_A1, 3); + for (int i = 1; i < NUM_REGS_SAVED; ++i) { + asm_xtensa_op_s32i_n(as, ASM_XTENSA_REG_A11 + i, ASM_XTENSA_REG_A1, i); + } } void asm_xtensa_exit(asm_xtensa_t *as) { // restore registers - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A14, ASM_XTENSA_REG_A1, 3); - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A13, ASM_XTENSA_REG_A1, 2); - asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A12, ASM_XTENSA_REG_A1, 1); + for (int i = NUM_REGS_SAVED - 1; i >= 1; --i) { + asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A11 + i, ASM_XTENSA_REG_A1, i); + } asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_A1, 0); // restore stack-pointer and return - asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, as->stack_adjust); + if (SIGNED_FIT8(as->stack_adjust)) { + asm_xtensa_op_addi(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, as->stack_adjust); + } else { + asm_xtensa_op_movi(as, ASM_XTENSA_REG_A9, as->stack_adjust); + asm_xtensa_op_add_n(as, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A1, ASM_XTENSA_REG_A9); + } + asm_xtensa_op_ret_n(as); } @@ -149,7 +161,8 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { asm_xtensa_op_movi(as, reg_dest, i32); } else { // load the constant - asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, 4 + as->cur_const * WORD_SIZE); + uint32_t const_table_offset = (uint8_t *)as->const_table - as->base.code_base; + asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, const_table_offset + as->cur_const * WORD_SIZE); // store the constant in the table if (as->const_table != NULL) { as->const_table[as->cur_const] = i32; @@ -159,16 +172,52 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { } void asm_xtensa_mov_local_reg(asm_xtensa_t *as, int local_num, uint reg_src) { - asm_xtensa_op_s32i(as, reg_src, ASM_XTENSA_REG_A1, 4 + local_num); + asm_xtensa_op_s32i(as, reg_src, ASM_XTENSA_REG_A1, NUM_REGS_SAVED + local_num); } void asm_xtensa_mov_reg_local(asm_xtensa_t *as, uint reg_dest, int local_num) { - asm_xtensa_op_l32i(as, reg_dest, ASM_XTENSA_REG_A1, 4 + local_num); + asm_xtensa_op_l32i(as, reg_dest, ASM_XTENSA_REG_A1, NUM_REGS_SAVED + local_num); } void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_num) { - asm_xtensa_op_mov_n(as, reg_dest, ASM_XTENSA_REG_A1); - asm_xtensa_op_addi(as, reg_dest, reg_dest, (4 + local_num) * WORD_SIZE); + uint off = (NUM_REGS_SAVED + local_num) * WORD_SIZE; + if (SIGNED_FIT8(off)) { + asm_xtensa_op_addi(as, reg_dest, ASM_XTENSA_REG_A1, off); + } else { + asm_xtensa_op_movi(as, reg_dest, off); + asm_xtensa_op_add_n(as, reg_dest, reg_dest, ASM_XTENSA_REG_A1); + } +} + +void asm_xtensa_mov_reg_pcrel(asm_xtensa_t *as, uint reg_dest, uint label) { + // Get relative offset from PC + uint32_t dest = get_label_dest(as, label); + int32_t rel = dest - as->base.code_offset; + rel -= 3 + 3; // account for 3 bytes of movi instruction, 3 bytes call0 adjustment + asm_xtensa_op_movi(as, reg_dest, rel); // imm has 12-bit range + + // Use call0 to get PC+3 into a0 + // call0 destination must be aligned on 4 bytes: + // - code_offset&3=0: off=0, pad=1 + // - code_offset&3=1: off=0, pad=0 + // - code_offset&3=2: off=1, pad=3 + // - code_offset&3=3: off=1, pad=2 + uint32_t off = as->base.code_offset >> 1 & 1; + uint32_t pad = (5 - as->base.code_offset) & 3; + asm_xtensa_op_call0(as, off); + mp_asm_base_get_cur_to_write_bytes(&as->base, pad); + + // Add PC to relative offset + asm_xtensa_op_add_n(as, reg_dest, reg_dest, ASM_XTENSA_REG_A0); +} + +void asm_xtensa_call_ind(asm_xtensa_t *as, uint idx) { + if (idx < 16) { + asm_xtensa_op_l32i_n(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_FUN_TABLE, idx); + } else { + asm_xtensa_op_l32i(as, ASM_XTENSA_REG_A0, ASM_XTENSA_REG_FUN_TABLE, idx); + } + asm_xtensa_op_callx0(as, ASM_XTENSA_REG_A0); } #endif // MICROPY_EMIT_XTENSA || MICROPY_EMIT_INLINE_XTENSA diff --git a/py/asmxtensa.h b/py/asmxtensa.h index d43824338d683..685b3f9492bf0 100644 --- a/py/asmxtensa.h +++ b/py/asmxtensa.h @@ -113,12 +113,12 @@ void asm_xtensa_op24(asm_xtensa_t *as, uint32_t op); // raw instructions -static inline void asm_xtensa_op_add(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { - asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRR(0, 0, 8, reg_dest, reg_src_a, reg_src_b)); +static inline void asm_xtensa_op_add_n(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { + asm_xtensa_op16(as, ASM_XTENSA_ENCODE_RRRN(10, reg_dest, reg_src_a, reg_src_b)); } static inline void asm_xtensa_op_addi(asm_xtensa_t *as, uint reg_dest, uint reg_src, int imm8) { - asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 12, reg_dest, reg_src, imm8 & 0xff)); + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 12, reg_src, reg_dest, imm8 & 0xff)); } static inline void asm_xtensa_op_and(asm_xtensa_t *as, uint reg_dest, uint reg_src_a, uint reg_src_b) { @@ -133,6 +133,10 @@ static inline void asm_xtensa_op_bccz(asm_xtensa_t *as, uint cond, uint reg_src, asm_xtensa_op24(as, ASM_XTENSA_ENCODE_BRI12(6, reg_src, cond, 1, rel12 & 0xfff)); } +static inline void asm_xtensa_op_call0(asm_xtensa_t *as, int32_t rel18) { + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_CALL(5, 0, rel18 & 0x3ffff)); +} + static inline void asm_xtensa_op_callx0(asm_xtensa_t *as, uint reg) { asm_xtensa_op24(as, ASM_XTENSA_ENCODE_CALLX(0, 0, 0, 0, reg, 3, 0)); } @@ -238,6 +242,11 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32); void asm_xtensa_mov_local_reg(asm_xtensa_t *as, int local_num, uint reg_src); void asm_xtensa_mov_reg_local(asm_xtensa_t *as, uint reg_dest, int local_num); void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_num); +void asm_xtensa_mov_reg_pcrel(asm_xtensa_t *as, uint reg_dest, uint label); +void asm_xtensa_call_ind(asm_xtensa_t *as, uint idx); + +// Holds a pointer to mp_fun_table +#define ASM_XTENSA_REG_FUN_TABLE ASM_XTENSA_REG_A15 #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -262,30 +271,29 @@ void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_nu #define REG_LOCAL_3 ASM_XTENSA_REG_A14 #define REG_LOCAL_NUM (3) +#define REG_FUN_TABLE ASM_XTENSA_REG_FUN_TABLE + #define ASM_T asm_xtensa_t #define ASM_END_PASS asm_xtensa_end_pass #define ASM_ENTRY asm_xtensa_entry #define ASM_EXIT asm_xtensa_exit #define ASM_JUMP asm_xtensa_j_label -#define ASM_JUMP_IF_REG_ZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ asm_xtensa_bccz_reg_label(as, ASM_XTENSA_CCZ_EQ, reg, label) -#define ASM_JUMP_IF_REG_NONZERO(as, reg, label) \ +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ asm_xtensa_bccz_reg_label(as, ASM_XTENSA_CCZ_NE, reg, label) #define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ asm_xtensa_bcc_reg_reg_label(as, ASM_XTENSA_CC_EQ, reg1, reg2, label) -#define ASM_CALL_IND(as, ptr, idx) \ - do { \ - asm_xtensa_mov_reg_i32(as, ASM_XTENSA_REG_A0, (uint32_t)ptr); \ - asm_xtensa_op_callx0(as, ASM_XTENSA_REG_A0); \ - } while (0) +#define ASM_JUMP_REG(as, reg) asm_xtensa_op_jx((as), (reg)) +#define ASM_CALL_IND(as, idx) asm_xtensa_call_ind((as), (idx)) #define ASM_MOV_LOCAL_REG(as, local_num, reg_src) asm_xtensa_mov_local_reg((as), (local_num), (reg_src)) #define ASM_MOV_REG_IMM(as, reg_dest, imm) asm_xtensa_mov_reg_i32((as), (reg_dest), (imm)) -#define ASM_MOV_REG_ALIGNED_IMM(as, reg_dest, imm) asm_xtensa_mov_reg_i32((as), (reg_dest), (imm)) #define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) asm_xtensa_mov_reg_local((as), (reg_dest), (local_num)) #define ASM_MOV_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_mov_n((as), (reg_dest), (reg_src)) #define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) asm_xtensa_mov_reg_local_addr((as), (reg_dest), (local_num)) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) asm_xtensa_mov_reg_pcrel((as), (reg_dest), (label)) #define ASM_LSL_REG_REG(as, reg_dest, reg_shift) \ do { \ @@ -300,7 +308,7 @@ void asm_xtensa_mov_reg_local_addr(asm_xtensa_t *as, uint reg_dest, int local_nu #define ASM_OR_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_or((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_XOR_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_xor((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_AND_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_and((as), (reg_dest), (reg_dest), (reg_src)) -#define ASM_ADD_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_add((as), (reg_dest), (reg_dest), (reg_src)) +#define ASM_ADD_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_add_n((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_SUB_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_sub((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_xtensa_op_mull((as), (reg_dest), (reg_dest), (reg_src)) diff --git a/py/bc.c b/py/bc.c index 01131cb4c02b1..1e2c0bbae1d2f 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; @@ -302,7 +302,7 @@ continue2:; // MP_BC_MAKE_CLOSURE_DEFARGS // MP_BC_RAISE_VARARGS // There are 4 special opcodes that have an extra byte only when -// MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE is enabled: +// MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE is enabled (and they take a qstr): // MP_BC_LOAD_NAME // MP_BC_LOAD_GLOBAL // MP_BC_LOAD_ATTR @@ -396,19 +396,21 @@ uint mp_opcode_format(const byte *ip, size_t *opcode_size) { uint f = (opcode_format_table[*ip >> 2] >> (2 * (*ip & 3))) & 3; const byte *ip_start = ip; if (f == MP_OPCODE_QSTR) { + if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE_DYNAMIC) { + if (*ip == MP_BC_LOAD_NAME + || *ip == MP_BC_LOAD_GLOBAL + || *ip == MP_BC_LOAD_ATTR + || *ip == MP_BC_STORE_ATTR) { + ip += 1; + } + } ip += 3; } else { int extra_byte = ( *ip == MP_BC_RAISE_VARARGS || *ip == MP_BC_MAKE_CLOSURE || *ip == MP_BC_MAKE_CLOSURE_DEFARGS - #if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - || *ip == MP_BC_LOAD_NAME - || *ip == MP_BC_LOAD_GLOBAL - || *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 b71325f92b758..6f62711c8702f 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 b85edba625c31..cd61d74fa8d51 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 @@ -329,29 +371,25 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** } } - if (val_type == 'x') { - memset(p, 0, 1); - } else { - mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val); - } + mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val); } 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 +399,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 +414,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/builtin.h b/py/builtin.h index 2275691fc858b..58c4c1e5248f5 100644 --- a/py/builtin.h +++ b/py/builtin.h @@ -106,6 +106,7 @@ extern const mp_obj_module_t mp_module_ujson; extern const mp_obj_module_t mp_module_ure; extern const mp_obj_module_t mp_module_uheapq; extern const mp_obj_module_t mp_module_uhashlib; +extern const mp_obj_module_t mp_module_ucryptolib; extern const mp_obj_module_t mp_module_ubinascii; extern const mp_obj_module_t mp_module_urandom; extern const mp_obj_module_t mp_module_uselect; diff --git a/py/builtinevex.c b/py/builtinevex.c index ade12d39d0f4c..5538ac783c115 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")); } @@ -132,17 +138,18 @@ STATIC mp_obj_t eval_exec_helper(size_t n_args, const mp_obj_t *args, mp_parse_i } #endif - size_t str_len; - const char *str = mp_obj_str_get_data(args[0], &str_len); + // Extract the source code. + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); // create the lexer // MP_PARSE_SINGLE_INPUT is used to indicate a file input mp_lexer_t *lex; if (MICROPY_PY_BUILTINS_EXECFILE && parse_input_kind == MP_PARSE_SINGLE_INPUT) { - lex = mp_lexer_new_from_file(str); + lex = mp_lexer_new_from_file(bufinfo.buf); parse_input_kind = MP_PARSE_FILE_INPUT; } else { - lex = mp_lexer_new_from_str_len(MP_QSTR__lt_string_gt_, str, str_len, 0); + lex = mp_lexer_new_from_str_len(MP_QSTR__lt_string_gt_, bufinfo.buf, bufinfo.len, 0); } return mp_parse_compile_execute(lex, parse_input_kind, globals, locals); diff --git a/py/builtinhelp.c b/py/builtinhelp.c index e1dcb60962044..225126029e437 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); @@ -167,13 +167,13 @@ STATIC void mp_help_print_obj(const mp_obj_t obj) { mp_map_t *map = NULL; if (type == &mp_type_module) { - map = mp_obj_dict_get_map(mp_obj_module_get_globals(obj)); + map = &mp_obj_module_get_globals(obj)->map; } else { if (type == &mp_type_type) { type = MP_OBJ_TO_PTR(obj); } - if (type->locals_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)) { - map = mp_obj_dict_get_map(type->locals_dict); + if (type->locals_dict != NULL) { + map = &type->locals_dict->map; } } if (map != NULL) { @@ -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 c4768cc777b41..8462c146b1532 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 + #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); - 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; - } + 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_defns.mk b/py/circuitpy_defns.mk index 3ce7c0117353c..93488d3d9088e 100644 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -139,6 +139,12 @@ endif ifeq ($(CIRCUITPY_BITBANG_APA102),1) SRC_PATTERNS += bitbangio/SPI% endif +ifeq ($(CIRCUITPY_BITMAPTOOLS),1) +SRC_PATTERNS += bitmaptools/% +endif +ifeq ($(CIRCUITPY_BITOPS),1) +SRC_PATTERNS += bitops/% +endif ifeq ($(CIRCUITPY_BLEIO),1) SRC_PATTERNS += _bleio/% endif @@ -274,6 +280,9 @@ endif ifeq ($(CIRCUITPY_SUPERVISOR),1) SRC_PATTERNS += supervisor/% endif +ifeq ($(CIRCUITPY_SYNTHIO),1) +SRC_PATTERNS += synthio/% +endif ifeq ($(CIRCUITPY_TERMINALIO),1) SRC_PATTERNS += terminalio/% fontio/% endif @@ -286,12 +295,18 @@ endif ifeq ($(CIRCUITPY_UHEAP),1) SRC_PATTERNS += uheap/% endif +ifeq ($(CIRCUITPY_USB_CDC),1) +SRC_PATTERNS += usb_cdc/% +endif ifeq ($(CIRCUITPY_USB_HID),1) SRC_PATTERNS += usb_hid/% endif ifeq ($(CIRCUITPY_USB_MIDI),1) SRC_PATTERNS += usb_midi/% endif +ifeq ($(CIRCUITPY_USB_VENDOR),1) +SRC_PATTERNS += usb_vendor/% +endif ifeq ($(CIRCUITPY_USTACK),1) SRC_PATTERNS += ustack/% endif @@ -304,6 +319,9 @@ endif ifeq ($(CIRCUITPY_PEW),1) SRC_PATTERNS += _pew/% endif +ifeq ($(CIRCUITPY_IMAGECAPTURE),1) +SRC_PATTERNS += imagecapture/% +endif ifeq ($(CIRCUITPY_MSGPACK),1) SRC_PATTERNS += msgpack/% endif @@ -352,8 +370,11 @@ SRC_COMMON_HAL_ALL = \ digitalio/DigitalInOut.c \ digitalio/__init__.c \ displayio/ParallelBus.c \ + dualbank/__init__.c \ frequencyio/FrequencyIn.c \ frequencyio/__init__.c \ + imagecapture/ParallelImageCapture.c \ + imagecapture/__init__.c \ gnss/__init__.c \ gnss/GNSS.c \ gnss/PositionFix.c \ @@ -367,7 +388,6 @@ SRC_COMMON_HAL_ALL = \ nvm/ByteArray.c \ nvm/__init__.c \ os/__init__.c \ - dualbank/__init__.c \ ps2io/Ps2.c \ ps2io/__init__.c \ pulseio/PulseIn.c \ @@ -388,6 +408,7 @@ SRC_COMMON_HAL_ALL = \ socketpool/Socket.c \ ssl/__init__.c \ ssl/SSLContext.c \ + ssl/SSLSocket.c \ supervisor/Runtime.c \ supervisor/__init__.c \ watchdog/WatchDogMode.c \ @@ -462,6 +483,8 @@ SRC_SHARED_MODULE_ALL = \ bitbangio/OneWire.c \ bitbangio/SPI.c \ bitbangio/__init__.c \ + bitmaptools/__init__.c \ + bitops/__init__.c \ board/__init__.c \ adafruit_bus_device/__init__.c \ adafruit_bus_device/I2CDevice.c \ @@ -503,11 +526,14 @@ SRC_SHARED_MODULE_ALL = \ random/__init__.c \ rgbmatrix/RGBMatrix.c \ rgbmatrix/__init__.c \ + rotaryio/IncrementalEncoder.c \ sharpdisplay/SharpMemoryFramebuffer.c \ sharpdisplay/__init__.c \ socket/__init__.c \ storage/__init__.c \ struct/__init__.c \ + synthio/MidiTrack.c \ + synthio/__init__.c \ terminalio/Terminal.c \ terminalio/__init__.c \ time/__init__.c \ diff --git a/py/circuitpy_mpconfig.h b/py/circuitpy_mpconfig.h index ee23c715698e5..15881f41bd54c 100644 --- a/py/circuitpy_mpconfig.h +++ b/py/circuitpy_mpconfig.h @@ -75,6 +75,7 @@ #define MICROPY_MODULE_BUILTIN_INIT (1) #define MICROPY_NONSTANDARD_TYPECODES (0) #define MICROPY_OPT_COMPUTED_GOTO (1) +#define MICROPY_OPT_COMPUTED_GOTO_SAVE_SPACE (CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE) #define MICROPY_PERSISTENT_CODE_LOAD (1) #define MICROPY_PY_ARRAY (1) @@ -147,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) @@ -306,6 +307,20 @@ extern const struct _mp_obj_module_t bitbangio_module; #define BITBANGIO_MODULE #endif +#if CIRCUITPY_BITMAPTOOLS +#define BITMAPTOOLS_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_bitmaptools), (mp_obj_t)&bitmaptools_module }, +extern const struct _mp_obj_module_t bitmaptools_module; +#else +#define BITMAPTOOLS_MODULE +#endif + +#if CIRCUITPY_BITOPS +extern const struct _mp_obj_module_t bitops_module; +#define BITOPS_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_bitops),(mp_obj_t)&bitops_module }, +#else +#define BITOPS_MODULE +#endif + #if CIRCUITPY_BLEIO #define BLEIO_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR__bleio), (mp_obj_t)&bleio_module }, extern const struct _mp_obj_module_t bleio_module; @@ -397,6 +412,13 @@ extern const struct _mp_obj_module_t terminalio_module; #define TERMINALIO_MODULE #endif +#if CIRCUITPY_DUALBANK +extern const struct _mp_obj_module_t dualbank_module; +#define DUALBANK_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_dualbank), (mp_obj_t)&dualbank_module }, +#else +#define DUALBANK_MODULE +#endif + #if CIRCUITPY_ERRNO #define MICROPY_PY_UERRNO (1) // Uses about 80 bytes. @@ -405,7 +427,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; @@ -471,6 +493,13 @@ extern const struct _mp_obj_module_t i2cperipheral_module; #define I2CPERIPHERAL_MODULE #endif +#if CIRCUITPY_IMAGECAPTURE +extern const struct _mp_obj_module_t imagecapture_module; +#define IMAGECAPTURE_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_imagecapture), (mp_obj_t)&imagecapture_module }, +#else +#define IMAGECAPTURE_MODULE +#endif + #if CIRCUITPY_IPADDRESS extern const struct _mp_obj_module_t ipaddress_module; #define IPADDRESS_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_ipaddress), (mp_obj_t)&ipaddress_module }, @@ -508,7 +537,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 @@ -535,7 +564,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 @@ -559,13 +588,6 @@ extern const struct _mp_obj_module_t os_module; #define OS_MODULE_ALT_NAME #endif -#if CIRCUITPY_DUALBANK -extern const struct _mp_obj_module_t dualbank_module; -#define DUALBANK_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_dualbank), (mp_obj_t)&dualbank_module }, -#else -#define DUALBANK_MODULE -#endif - #if CIRCUITPY_PEW extern const struct _mp_obj_module_t pew_module; #define PEW_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR__pew),(mp_obj_t)&pew_module }, @@ -713,6 +735,13 @@ extern const struct _mp_obj_module_t supervisor_module; #define SUPERVISOR_MODULE #endif +#if CIRCUITPY_SYNTHIO +#define SYNTHIO_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_synthio), (mp_obj_t)&synthio_module }, +extern const struct _mp_obj_module_t synthio_module; +#else +#define SYNTHIO_MODULE +#endif + #if CIRCUITPY_TIME extern const struct _mp_obj_module_t time_module; #define TIME_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_time), (mp_obj_t)&time_module }, @@ -736,6 +765,13 @@ extern const struct _mp_obj_module_t uheap_module; #define UHEAP_MODULE #endif +#if CIRCUITPY_USB_CDC +extern const struct _mp_obj_module_t usb_cdc_module; +#define USB_CDC_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_usb_cdc),(mp_obj_t)&usb_cdc_module }, +#else +#define USB_CDC_MODULE +#endif + #if CIRCUITPY_USB_HID extern const struct _mp_obj_module_t usb_hid_module; #define USB_HID_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_usb_hid),(mp_obj_t)&usb_hid_module }, @@ -820,6 +856,8 @@ extern const struct _mp_obj_module_t msgpack_module; AUDIOPWMIO_MODULE \ BINASCII_MODULE \ BITBANGIO_MODULE \ + BITMAPTOOLS_MODULE \ + BITOPS_MODULE \ BLEIO_MODULE \ BOARD_MODULE \ BUSDEVICE_MODULE \ @@ -829,9 +867,10 @@ extern const struct _mp_obj_module_t msgpack_module; COUNTIO_MODULE \ DIGITALIO_MODULE \ DISPLAYIO_MODULE \ - FONTIO_MODULE \ - TERMINALIO_MODULE \ - VECTORIO_MODULE \ + DUALBANK_MODULE \ + FONTIO_MODULE \ + TERMINALIO_MODULE \ + VECTORIO_MODULE \ ERRNO_MODULE \ ESPIDF_MODULE \ FRAMEBUFFERIO_MODULE \ @@ -841,6 +880,7 @@ extern const struct _mp_obj_module_t msgpack_module; GNSS_MODULE \ I2CPERIPHERAL_MODULE \ IPADDRESS_MODULE \ + IMAGECAPTURE_MODULE \ JSON_MODULE \ MATH_MODULE \ _EVE_MODULE \ @@ -849,9 +889,8 @@ extern const struct _mp_obj_module_t msgpack_module; MSGPACK_MODULE \ NEOPIXEL_WRITE_MODULE \ NETWORK_MODULE \ - SOCKET_MODULE \ - WIZNET_MODULE \ - DUALBANK_MODULE \ + SOCKET_MODULE \ + WIZNET_MODULE \ PEW_MODULE \ PIXELBUF_MODULE \ PS2IO_MODULE \ @@ -873,8 +912,10 @@ extern const struct _mp_obj_module_t msgpack_module; STORAGE_MODULE \ STRUCT_MODULE \ SUPERVISOR_MODULE \ + SYNTHIO_MODULE \ TOUCHIO_MODULE \ UHEAP_MODULE \ + USB_CDC_MODULE \ USB_HID_MODULE \ USB_MIDI_MODULE \ USTACK_MODULE \ @@ -913,8 +954,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/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk index b8fe73eea999a..7dd44f4172afc 100644 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -89,9 +89,15 @@ CFLAGS += -DCIRCUITPY_AUDIOMP3=$(CIRCUITPY_AUDIOMP3) CIRCUITPY_BINASCII ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_BINASCII=$(CIRCUITPY_BINASCII) +CIRCUITPY_BITBANG_APA102 ?= 0 +CFLAGS += -DCIRCUITPY_BITBANG_APA102=$(CIRCUITPY_BITBANG_APA102) + CIRCUITPY_BITBANGIO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_BITBANGIO=$(CIRCUITPY_BITBANGIO) +CIRCUITPY_BITOPS ?= 0 +CFLAGS += -DCIRCUITPY_BITOPS=$(CIRCUITPY_BITOPS) + # _bleio can be supported on most any board via HCI CIRCUITPY_BLEIO_HCI ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_BLEIO_HCI=$(CIRCUITPY_BLEIO_HCI) @@ -100,6 +106,9 @@ CFLAGS += -DCIRCUITPY_BLEIO_HCI=$(CIRCUITPY_BLEIO_HCI) CIRCUITPY_BLEIO ?= $(CIRCUITPY_BLEIO_HCI) CFLAGS += -DCIRCUITPY_BLEIO=$(CIRCUITPY_BLEIO) +CIRCUITPY_BLE_FILE_SERVICE ?= 0 +CFLAGS += -DCIRCUITPY_BLE_FILE_SERVICE=$(CIRCUITPY_BLE_FILE_SERVICE) + CIRCUITPY_BOARD ?= 1 CFLAGS += -DCIRCUITPY_BOARD=$(CIRCUITPY_BOARD) @@ -121,12 +130,22 @@ CFLAGS += -DCIRCUITPY_CANIO=$(CIRCUITPY_CANIO) CIRCUITPY_DIGITALIO ?= 1 CFLAGS += -DCIRCUITPY_DIGITALIO=$(CIRCUITPY_DIGITALIO) +CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE ?= 0 +CFLAGS += -DCIRCUITPY_COMPUTED_GOTO_SAVE_SPACE=$(CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE) + CIRCUITPY_COUNTIO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_COUNTIO=$(CIRCUITPY_COUNTIO) CIRCUITPY_DISPLAYIO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_DISPLAYIO=$(CIRCUITPY_DISPLAYIO) +CIRCUITPY_DUALBANK ?= 0 +CFLAGS += -DCIRCUITPY_DUALBANK=$(CIRCUITPY_DUALBANK) + +# Enabled micropython.native decorator (experimental) +CIRCUITPY_ENABLE_MPY_NATIVE ?= 0 +CFLAGS += -DCIRCUITPY_ENABLE_MPY_NATIVE=$(CIRCUITPY_ENABLE_MPY_NATIVE) + CIRCUITPY_ERRNO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_ERRNO=$(CIRCUITPY_ERRNO) @@ -136,11 +155,15 @@ CFLAGS += -DCIRCUITPY_ERRNO=$(CIRCUITPY_ERRNO) CIRCUITPY_ESPIDF ?= 0 CFLAGS += -DCIRCUITPY_ESPIDF=$(CIRCUITPY_ESPIDF) +# bitmaptools and framebufferio rely on displayio ifeq ($(CIRCUITPY_DISPLAYIO),1) +CIRCUITPY_BITMAPTOOLS ?= $(CIRCUITPY_FULL_BUILD) CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_FULL_BUILD) else +CIRCUITPY_BITMAPTOOLS ?= 0 CIRCUITPY_FRAMEBUFFERIO ?= 0 endif +CFLAGS += -DCIRCUITPY_BITMAPTOOLS=$(CIRCUITPY_BITMAPTOOLS) CFLAGS += -DCIRCUITPY_FRAMEBUFFERIO=$(CIRCUITPY_FRAMEBUFFERIO) CIRCUITPY_VECTORIO ?= $(CIRCUITPY_DISPLAYIO) @@ -179,6 +202,9 @@ CFLAGS += -DCIRCUITPY_MEMORYMONITOR=$(CIRCUITPY_MEMORYMONITOR) CIRCUITPY_MICROCONTROLLER ?= 1 CFLAGS += -DCIRCUITPY_MICROCONTROLLER=$(CIRCUITPY_MICROCONTROLLER) +CIRCUITPY_MSGPACK ?= $(CIRCUITPY_FULL_BUILD) +CFLAGS += -DCIRCUITPY_MSGPACK=$(CIRCUITPY_MSGPACK) + CIRCUITPY_NEOPIXEL_WRITE ?= 1 CFLAGS += -DCIRCUITPY_NEOPIXEL_WRITE=$(CIRCUITPY_NEOPIXEL_WRITE) @@ -192,8 +218,11 @@ CFLAGS += -DCIRCUITPY_NVM=$(CIRCUITPY_NVM) CIRCUITPY_OS ?= 1 CFLAGS += -DCIRCUITPY_OS=$(CIRCUITPY_OS) -CIRCUITPY_DUALBANK ?= 0 -CFLAGS += -DCIRCUITPY_DUALBANK=$(CIRCUITPY_DUALBANK) +CIRCUITPY_IMAGECAPTURE ?= 0 +CFLAGS += -DCIRCUITPY_IMAGECAPTURE=$(CIRCUITPY_IMAGECAPTURE) + +CIRCUITPY_PEW ?= 0 +CFLAGS += -DCIRCUITPY_PEW=$(CIRCUITPY_PEW) CIRCUITPY_PIXELBUF ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_PIXELBUF=$(CIRCUITPY_PIXELBUF) @@ -216,6 +245,23 @@ CFLAGS += -DCIRCUITPY_RANDOM=$(CIRCUITPY_RANDOM) CIRCUITPY_RE ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_RE=$(CIRCUITPY_RE) +CIRCUITPY_RE_DEBUG ?= 0 +CFLAGS += -DCIRCUITPY_RE_DEBUG=$(CIRCUITPY_RE_DEBUG) + +CIRCUITPY_REPL_BLE ?= 0 +CFLAGS += -DCIRCUITPY_REPL_BLE=$(CIRCUITPY_REPL_BLE) + +CIRCUITPY_REPL_UART ?= 0 +CFLAGS += -DCIRCUITPY_REPL_UART=$(CIRCUITPY_REPL_UART) + +CIRCUITPY_REPL_USB ?= 1 +CFLAGS += -DCIRCUITPY_REPL_USB=$(CIRCUITPY_REPL_USB) + +# Should busio.I2C() check for pullups? +# Some boards in combination with certain peripherals may not want this. +CIRCUITPY_REQUIRE_I2C_PULLUPS ?= 1 +CFLAGS += -DCIRCUITPY_REQUIRE_I2C_PULLUPS=$(CIRCUITPY_REQUIRE_I2C_PULLUPS) + # CIRCUITPY_RP2PIO is handled in the raspberrypi tree. # Only for rp2 chips. # Assume not a rp2 build. @@ -228,6 +274,9 @@ CFLAGS += -DCIRCUITPY_RGBMATRIX=$(CIRCUITPY_RGBMATRIX) CIRCUITPY_ROTARYIO ?= 1 CFLAGS += -DCIRCUITPY_ROTARYIO=$(CIRCUITPY_ROTARYIO) +CIRCUITPY_ROTARYIO_SOFTENCODER ?= 0 +CFLAGS += -DCIRCUITPY_ROTARYIO_SOFTENCODER=$(CIRCUITPY_ROTARYIO_SOFTENCODER) + CIRCUITPY_RTC ?= 1 CFLAGS += -DCIRCUITPY_RTC=$(CIRCUITPY_RTC) @@ -265,6 +314,9 @@ CFLAGS += -DCIRCUITPY_STRUCT=$(CIRCUITPY_STRUCT) CIRCUITPY_SUPERVISOR ?= 1 CFLAGS += -DCIRCUITPY_SUPERVISOR=$(CIRCUITPY_SUPERVISOR) +CIRCUITPY_SYNTHIO ?= $(CIRCUITPY_AUDIOCORE) +CFLAGS += -DCIRCUITPY_SYNTHIO=$(CIRCUITPY_SYNTHIO) + CIRCUITPY_TERMINALIO ?= $(CIRCUITPY_DISPLAYIO) CFLAGS += -DCIRCUITPY_TERMINALIO=$(CIRCUITPY_TERMINALIO) @@ -282,39 +334,58 @@ CFLAGS += -DCIRCUITPY_TOUCHIO=$(CIRCUITPY_TOUCHIO) CIRCUITPY_UHEAP ?= 0 CFLAGS += -DCIRCUITPY_UHEAP=$(CIRCUITPY_UHEAP) +CIRCUITPY_USB ?= 1 +CFLAGS += -DCIRCUITPY_USB=$(CIRCUITPY_USB) + +# Disable by default for now, until we have dynamic enabling. +CIRCUITPY_USB_CDC ?= 0 +# Secondary CDC is usually available if there are at least 8 endpoints. +#CIRCUITPY_USB_CDC ?= $(shell expr $(USB_NUM_EP) '>=' 8) +CFLAGS += -DCIRCUITPY_USB_CDC=$(CIRCUITPY_USB_CDC) + CIRCUITPY_USB_HID ?= 1 CFLAGS += -DCIRCUITPY_USB_HID=$(CIRCUITPY_USB_HID) -CIRCUITPY_USB_MIDI ?= 1 -CFLAGS += -DCIRCUITPY_USB_MIDI=$(CIRCUITPY_USB_MIDI) +CIRCUITPY_USB_HID_CONSUMER ?= 1 +CFLAGS += -DCIRCUITPY_USB_HID_CONSUMER=$(CIRCUITPY_USB_HID_CONSUMER) -CIRCUITPY_PEW ?= 0 -CFLAGS += -DCIRCUITPY_PEW=$(CIRCUITPY_PEW) +CIRCUITPY_USB_HID_DIGITIZER ?= 0 +CFLAGS += -DCIRCUITPY_USB_HID_DIGITIZER=$(CIRCUITPY_USB_HID_DIGITIZER) -# For debugging. -CIRCUITPY_USTACK ?= 0 -CFLAGS += -DCIRCUITPY_USTACK=$(CIRCUITPY_USTACK) +CIRCUITPY_USB_HID_GAMEPAD ?= 1 +CFLAGS += -DCIRCUITPY_USB_HID_GAMEPAD=$(CIRCUITPY_USB_HID_GAMEPAD) -# Non-module conditionals +CIRCUITPY_USB_HID_KEYBOARD ?= 1 +CFLAGS += -DCIRCUITPY_USB_HID_KEYBOARD=$(CIRCUITPY_USB_HID_KEYBOARD) -CIRCUITPY_BITBANG_APA102 ?= 0 -CFLAGS += -DCIRCUITPY_BITBANG_APA102=$(CIRCUITPY_BITBANG_APA102) +CIRCUITPY_USB_HID_MOUSE ?= 1 +CFLAGS += -DCIRCUITPY_USB_HID_MOUSE=$(CIRCUITPY_USB_HID_MOUSE) -# Should busio.I2C() check for pullups? -# Some boards in combination with certain peripherals may not want this. -CIRCUITPY_REQUIRE_I2C_PULLUPS ?= 1 -CFLAGS += -DCIRCUITPY_REQUIRE_I2C_PULLUPS=$(CIRCUITPY_REQUIRE_I2C_PULLUPS) +CIRCUITPY_USB_HID_SYS_CONTROL ?= 0 +CFLAGS += -DCIRCUITPY_USB_HID_SYS_CONTROL=$(CIRCUITPY_USB_HID_SYS_CONTROL) -# REPL over BLE -CIRCUITPY_SERIAL_BLE ?= 0 -CFLAGS += -DCIRCUITPY_SERIAL_BLE=$(CIRCUITPY_SERIAL_BLE) +CIRCUITPY_USB_HID_XAC_COMPATIBLE_GAMEPAD ?= 0 +CFLAGS += -DCIRCUITPY_USB_HID_XAC_COMPATIBLE_GAMEPAD=$(CIRCUITPY_USB_HID_XAC_COMPATIBLE_GAMEPAD) -CIRCUITPY_BLE_FILE_SERVICE ?= 0 -CFLAGS += -DCIRCUITPY_BLE_FILE_SERVICE=$(CIRCUITPY_BLE_FILE_SERVICE) +CIRCUITPY_USB_MIDI ?= 1 +CFLAGS += -DCIRCUITPY_USB_MIDI=$(CIRCUITPY_USB_MIDI) + +CIRCUITPY_USB_MSC ?= 1 +CFLAGS += -DCIRCUITPY_USB_MSC=$(CIRCUITPY_USB_MSC) + +# Defaulting this to OFF initially because it has only been tested on a +# limited number of platforms, and the other platforms do not have this +# setting in their mpconfigport.mk and/or mpconfigboard.mk files yet. +CIRCUITPY_USB_VENDOR ?= 0 +CFLAGS += -DCIRCUITPY_USB_VENDOR=$(CIRCUITPY_USB_VENDOR) -# REPL over UART -CIRCUITPY_SERIAL_UART ?= 0 -CFLAGS += -DCIRCUITPY_SERIAL_UART=$(CIRCUITPY_SERIAL_UART) +ifndef USB_NUM_EP +$(error "USB_NUM_EP (number of USB endpoint pairs)must be defined") +endif + +# For debugging. +CIRCUITPY_USTACK ?= 0 +CFLAGS += -DCIRCUITPY_USTACK=$(CIRCUITPY_USTACK) # ulab numerics library CIRCUITPY_ULAB ?= $(CIRCUITPY_FULL_BUILD) @@ -326,10 +397,3 @@ CFLAGS += -DCIRCUITPY_WATCHDOG=$(CIRCUITPY_WATCHDOG) CIRCUITPY_WIFI ?= 0 CFLAGS += -DCIRCUITPY_WIFI=$(CIRCUITPY_WIFI) - -# Enabled micropython.native decorator (experimental) -CIRCUITPY_ENABLE_MPY_NATIVE ?= 0 -CFLAGS += -DCIRCUITPY_ENABLE_MPY_NATIVE=$(CIRCUITPY_ENABLE_MPY_NATIVE) - -CIRCUITPY_MSGPACK ?= $(CIRCUITPY_FULL_BUILD) -CFLAGS += -DCIRCUITPY_MSGPACK=$(CIRCUITPY_MSGPACK) diff --git a/py/compile.c b/py/compile.c index b4d81ed4451ee..a484022bb91e2 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; } } @@ -172,7 +172,18 @@ STATIC uint comp_next_label(compiler_t *comp) { return comp->next_label++; } -STATIC void compile_increase_except_level(compiler_t *comp) { +#if MICROPY_EMIT_NATIVE +STATIC void reserve_labels_for_native(compiler_t *comp, int n) { + if (comp->scope_cur->emit_options != MP_EMIT_OPT_BYTECODE) { + comp->next_label += n; + } +} +#else +#define reserve_labels_for_native(comp, n) +#endif + +STATIC void compile_increase_except_level(compiler_t *comp, uint label, int kind) { + EMIT_ARG(setup_block, label, kind); comp->cur_except_level += 1; if (comp->cur_except_level > comp->scope_cur->exc_stack_size) { comp->scope_cur->exc_stack_size = comp->cur_except_level; @@ -182,6 +193,8 @@ STATIC void compile_increase_except_level(compiler_t *comp) { STATIC void compile_decrease_except_level(compiler_t *comp) { assert(comp->cur_except_level > 0); comp->cur_except_level -= 1; + EMIT(end_finally); + reserve_labels_for_native(comp, 1); } STATIC scope_t *scope_new_and_link(compiler_t *comp, scope_kind_t kind, mp_parse_node_t pn, uint emit_options) { @@ -204,7 +217,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 +308,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 +367,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 +376,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 +436,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 +471,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 +497,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 +511,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 +524,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 +544,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")); } @@ -556,6 +569,11 @@ STATIC void close_over_variables_etc(compiler_t *comp, scope_t *this_scope, int } this_scope->num_def_pos_args = n_pos_defaults; + #if MICROPY_EMIT_NATIVE + // When creating a function/closure it will take a reference to the current globals + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS | MP_SCOPE_FLAG_HASCONSTS; + #endif + // make closed over variables, if any // ensure they are closed over in the order defined in the outer scope (mainly to agree with CPython) int nfree = 0; @@ -590,7 +608,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 +638,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 +737,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 +759,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); @@ -768,14 +786,14 @@ STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_ } if (name_len != 2) { - compile_syntax_error(comp, name_nodes[0], translate("invalid micropython decorator")); + compile_syntax_error(comp, name_nodes[0], translate("invalid decorator")); return true; } 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 +802,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 +831,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 +861,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 +897,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 +925,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 +954,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 +1000,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 +1028,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 +1045,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 +1064,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 +1123,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 +1167,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 +1178,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])) { @@ -1173,23 +1191,24 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { } } -STATIC void compile_declare_global(compiler_t *comp, mp_parse_node_t pn, qstr qst, bool added, id_info_t *id_info) { - if (!added && id_info->kind != ID_INFO_KIND_GLOBAL_EXPLICIT) { +STATIC void compile_declare_global(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) { + if (id_info->kind != ID_INFO_KIND_UNDECIDED && id_info->kind != ID_INFO_KIND_GLOBAL_EXPLICIT) { compile_syntax_error(comp, pn, translate("identifier redefined as global")); return; } id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; // if the id exists in the global scope, set its kind to EXPLICIT_GLOBAL - id_info = scope_find_global(comp->scope_cur, qst); + id_info = scope_find_global(comp->scope_cur, id_info->qst); if (id_info != NULL) { id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; } } -STATIC void compile_declare_nonlocal(compiler_t *comp, mp_parse_node_t pn, qstr qst, bool added, id_info_t *id_info) { - if (added) { - scope_find_local_and_close_over(comp->scope_cur, id_info, qst); +STATIC void compile_declare_nonlocal(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) { + if (id_info->kind == ID_INFO_KIND_UNDECIDED) { + id_info->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; + scope_check_to_close_over(comp->scope_cur, id_info); if (id_info->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { compile_syntax_error(comp, pn, translate("no binding for nonlocal found")); } @@ -1211,12 +1230,11 @@ STATIC void compile_global_nonlocal_stmt(compiler_t *comp, mp_parse_node_struct_ int n = mp_parse_node_extract_list(&pns->nodes[0], PN_name_list, &nodes); for (int i = 0; i < n; i++) { qstr qst = MP_PARSE_NODE_LEAF_ARG(nodes[i]); - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qst, &added); + id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qst, ID_INFO_KIND_UNDECIDED); if (is_global) { - compile_declare_global(comp, (mp_parse_node_t)pns, qst, added, id_info); + compile_declare_global(comp, (mp_parse_node_t)pns, id_info); } else { - compile_declare_nonlocal(comp, (mp_parse_node_t)pns, qst, added, id_info); + compile_declare_nonlocal(comp, (mp_parse_node_t)pns, id_info); } } } @@ -1273,7 +1291,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 +1460,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 +1493,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; } @@ -1524,8 +1542,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ uint l1 = comp_next_label(comp); uint success_label = comp_next_label(comp); - EMIT_ARG(setup_block, l1, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l1, MP_EMIT_SETUP_BLOCK_EXCEPT); compile_node(comp, pn_body); // body EMIT(pop_block); @@ -1540,7 +1557,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 +1573,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]; @@ -1579,8 +1596,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ uint l3 = 0; if (qstr_exception_local != 0) { l3 = comp_next_label(comp); - EMIT_ARG(setup_block, l3, MP_EMIT_SETUP_BLOCK_FINALLY); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l3, MP_EMIT_SETUP_BLOCK_FINALLY); } compile_node(comp, pns_except->nodes[1]); if (qstr_exception_local != 0) { @@ -1595,7 +1611,6 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ compile_delete_id(comp, qstr_exception_local); compile_decrease_except_level(comp); - EMIT(end_finally); } EMIT_ARG(jump, l2); EMIT_ARG(label_assign, end_finally_label); @@ -1603,7 +1618,6 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ } compile_decrease_except_level(comp); - EMIT(end_finally); EMIT(end_except_handler); EMIT_ARG(label_assign, success_label); @@ -1614,8 +1628,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n_except, mp_parse_node_t *pn_except, mp_parse_node_t pn_else, mp_parse_node_t pn_finally) { uint l_finally_block = comp_next_label(comp); - EMIT_ARG(setup_block, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); - compile_increase_except_level(comp); + compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); if (n_except == 0) { assert(MP_PARSE_NODE_IS_NULL(pn_else)); @@ -1631,13 +1644,12 @@ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n compile_node(comp, pn_finally); compile_decrease_except_level(comp); - EMIT(end_finally); } 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 +1662,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 @@ -1667,30 +1679,24 @@ STATIC void compile_with_stmt_helper(compiler_t *comp, int n, mp_parse_node_t *n compile_node(comp, body); } else { uint l_end = comp_next_label(comp); - if (MICROPY_EMIT_NATIVE && comp->scope_cur->emit_options != MP_EMIT_OPT_BYTECODE) { - // we need to allocate an extra label for the native emitter - // it will use l_end+1 as an auxiliary label - comp_next_label(comp); - } 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); + compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH); c_assign(comp, pns->nodes[1], ASSIGN_STORE); } else { // this pre-bit is just an expression compile_node(comp, nodes[0]); - EMIT_ARG(setup_block, l_end, MP_EMIT_SETUP_BLOCK_WITH); + compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH); EMIT(pop_top); } - compile_increase_except_level(comp); // compile additional pre-bits and the body compile_with_stmt_helper(comp, n - 1, nodes + 1, body); // finish this with block EMIT_ARG(with_cleanup, l_end); + reserve_labels_for_native(comp, 3); // used by native's with_cleanup compile_decrease_except_level(comp); - EMIT(end_finally); } } @@ -1708,12 +1714,13 @@ STATIC void compile_yield_from(compiler_t *comp) { EMIT_ARG(get_iter, false); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(yield, MP_EMIT_YIELD_FROM); + reserve_labels_for_native(comp, 3); } #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 +1737,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; } @@ -1749,8 +1756,7 @@ STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns EMIT_ARG(label_assign, continue_label); - EMIT_ARG(setup_block, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); + compile_increase_except_level(comp, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); compile_load_id(comp, context); compile_await_object_method(comp, MP_QSTR___anext__); @@ -1771,7 +1777,6 @@ STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns EMIT_ARG(label_assign, try_finally_label); EMIT_ARG(adjust_stack_size, 1); // if we jump here, the exc is on the stack compile_decrease_except_level(comp); - EMIT(end_finally); EMIT(end_except_handler); EMIT_ARG(label_assign, try_else_label); @@ -1792,46 +1797,70 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod // no more pre-bits, compile the body of the with compile_node(comp, body); } else { - uint try_exception_label = comp_next_label(comp); - uint no_reraise_label = comp_next_label(comp); - uint try_else_label = comp_next_label(comp); - uint end_label = comp_next_label(comp); - qstr context; + uint l_finally_block = comp_next_label(comp); + uint l_aexit_no_exc = comp_next_label(comp); + uint l_ret_unwind_jump = comp_next_label(comp); + uint l_end = comp_next_label(comp); 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); - compile_load_id(comp, context); + EMIT(dup_top); compile_await_object_method(comp, MP_QSTR___aenter__); c_assign(comp, pns->nodes[1], ASSIGN_STORE); } else { // this pre-bit is just an expression compile_node(comp, nodes[0]); - context = MP_PARSE_NODE_LEAF_ARG(nodes[0]); - compile_store_id(comp, context); - compile_load_id(comp, context); + EMIT(dup_top); compile_await_object_method(comp, MP_QSTR___aenter__); EMIT(pop_top); } - compile_load_id(comp, context); - EMIT_ARG(load_method, MP_QSTR___aexit__, false); + // To keep the Python stack size down, and because we can't access values on + // this stack further down than 3 elements (via rot_three), we don't preload + // __aexit__ (as per normal with) but rather wait until we need it below. - EMIT_ARG(setup_block, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT); - compile_increase_except_level(comp); - // compile additional pre-bits and the body + // Start the try-finally statement + compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY); + + // Compile any additional pre-bits of the "async with", and also the body + EMIT_ARG(adjust_stack_size, 3); // stack adjust for possible UNWIND_JUMP state compile_async_with_stmt_helper(comp, n - 1, nodes + 1, body); - // finish this with block + EMIT_ARG(adjust_stack_size, -3); + + // Finish the "try" block EMIT(pop_block); - EMIT_ARG(jump, try_else_label); // jump over exception handler - EMIT_ARG(label_assign, try_exception_label); // start of exception handler - EMIT(start_except_handler); + // At this point, after the with body has executed, we have 3 cases: + // 1. no exception, we just fall through to this point; stack: (..., ctx_mgr) + // 2. exception propagating out, we get to the finally block; stack: (..., ctx_mgr, exc) + // 3. return or unwind jump, we get to the finally block; stack: (..., ctx_mgr, X, INT) + + // Handle case 1: call __aexit__ + // Stack: (..., ctx_mgr) + EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // to tell end_finally there's no exception + EMIT(rot_two); + EMIT_ARG(jump, l_aexit_no_exc); // jump to code below to call __aexit__ + + // Start of "finally" block + // At this point we have case 2 or 3, we detect which one by the TOS being an exception or not + EMIT_ARG(label_assign, l_finally_block); - // at this point the stack contains: ..., __aexit__, self, exc + // Detect if TOS an exception or not + EMIT(dup_top); + EMIT_LOAD_GLOBAL(MP_QSTR_Exception); + EMIT_ARG(binary_op, MP_BINARY_OP_EXCEPTION_MATCH); + EMIT_ARG(pop_jump_if, false, l_ret_unwind_jump); // if not an exception then we have case 3 + + // Handle case 2: call __aexit__ and either swallow or re-raise the exception + // Stack: (..., ctx_mgr, exc) + EMIT(dup_top); + EMIT(rot_three); + EMIT(rot_two); + EMIT_ARG(load_method, MP_QSTR___aexit__, false); + EMIT(rot_three); + EMIT(rot_three); EMIT(dup_top); #if MICROPY_CPYTHON_COMPAT EMIT_ARG(attr, MP_QSTR___class__, MP_EMIT_ATTR_LOAD); // get type(exc) @@ -1842,37 +1871,42 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod #endif EMIT(rot_two); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // dummy traceback value - // at this point the stack contains: ..., __aexit__, self, type(exc), exc, None + // Stack: (..., exc, __aexit__, ctx_mgr, type(exc), exc, None) EMIT_ARG(call_method, 3, 0, 0); - compile_yield_from(comp); - EMIT_ARG(pop_jump_if, true, no_reraise_label); - EMIT_ARG(raise_varargs, 0); - - EMIT_ARG(label_assign, no_reraise_label); - EMIT(pop_except); - EMIT_ARG(jump, end_label); - - EMIT_ARG(adjust_stack_size, 3); // adjust for __aexit__, self, exc - compile_decrease_except_level(comp); - EMIT(end_finally); - EMIT(end_except_handler); - - EMIT_ARG(label_assign, try_else_label); // start of try-else handler + EMIT_ARG(pop_jump_if, false, l_end); + EMIT(pop_top); // pop exception + EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // replace with None to swallow exception + EMIT_ARG(jump, l_end); + EMIT_ARG(adjust_stack_size, 2); + + // Handle case 3: call __aexit__ + // Stack: (..., ctx_mgr, X, INT) + EMIT_ARG(label_assign, l_ret_unwind_jump); + EMIT(rot_three); + EMIT(rot_three); + EMIT_ARG(label_assign, l_aexit_no_exc); + EMIT_ARG(load_method, MP_QSTR___aexit__, false); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT(dup_top); EMIT(dup_top); EMIT_ARG(call_method, 3, 0, 0); compile_yield_from(comp); EMIT(pop_top); + EMIT_ARG(adjust_stack_size, -1); - EMIT_ARG(label_assign, end_label); - + // End of "finally" block + // Stack can have one of three configurations: + // a. (..., None) - from either case 1, or case 2 with swallowed exception + // b. (..., exc) - from case 2 with re-raised exception + // c. (..., X, INT) - from case 3 + EMIT_ARG(label_assign, l_end); + compile_decrease_except_level(comp); } } 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 +1920,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 +1957,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 +1965,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 +2024,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 +2075,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 +2097,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 +2138,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 +2216,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 +2251,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 +2276,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 +2369,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 +2401,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 +2442,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 +2452,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 +2470,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 +2490,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 +2501,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 +2523,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 +2541,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 +2549,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 +2579,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 +2589,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 +2621,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 +2651,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 +2664,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 +2679,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:] @@ -2630,19 +2722,21 @@ STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); } 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 { compile_node(comp, pns->nodes[0]); EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); } } @@ -2675,16 +2769,19 @@ STATIC mp_obj_t get_const_object(mp_parse_node_struct_t *pns) { } STATIC void compile_const_object(compiler_t *comp, mp_parse_node_struct_t *pns) { + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif 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 @@ -2697,7 +2794,7 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) { mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn); #if MICROPY_DYNAMIC_COMPILER - mp_uint_t sign_mask = -(1 << (mp_dynamic_compiler.small_int_bits - 1)); + mp_uint_t sign_mask = -((mp_uint_t)1 << (mp_dynamic_compiler.small_int_bits - 1)); if ((arg & sign_mask) == 0 || (arg & sign_mask) == sign_mask) { // integer fits in target runtime's small-int EMIT_ARG(load_const_small_int, arg); @@ -2709,6 +2806,9 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } else { EMIT_ARG(load_const_obj, mp_obj_new_int_from_ll(arg)); } + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif } #else EMIT_ARG(load_const_small_int, arg); @@ -2716,8 +2816,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) { @@ -2727,19 +2831,23 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { const byte *data = qstr_data(arg, &len); EMIT_ARG(load_const_obj, mp_obj_new_bytes(data, len)); } + #if MICROPY_EMIT_NATIVE + comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; + #endif 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)]; @@ -2747,6 +2855,25 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } } +#if MICROPY_EMIT_NATIVE +STATIC int compile_viper_type_annotation(compiler_t *comp, mp_parse_node_t pn_annotation) { + int native_type = MP_NATIVE_TYPE_OBJ; + if (MP_PARSE_NODE_IS_NULL(pn_annotation)) { + // No annotation, type defaults to object + } else if (MP_PARSE_NODE_IS_ID(pn_annotation)) { + qstr type_name = MP_PARSE_NODE_LEAF_ARG(pn_annotation); + native_type = mp_native_type_from_qstr(type_name); + if (native_type < 0) { + comp->compile_error = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, translate("unknown type '%q'"), type_name); + native_type = 0; + } + } else { + compile_syntax_error(comp, pn_annotation, translate("annotation must be an identifier")); + } + return native_type; +} +#endif + STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_name, pn_kind_t pn_star, pn_kind_t pn_dbl_star) { // check that **kw is last if ((comp->scope_cur->scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0) { @@ -2756,6 +2883,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn qstr param_name = MP_QSTR_NULL; uint param_flag = ID_FLAG_IS_PARAM; + mp_parse_node_struct_t *pns = NULL; if (MP_PARSE_NODE_IS_ID(pn)) { param_name = MP_PARSE_NODE_LEAF_ARG(pn); if (comp->have_star) { @@ -2767,8 +2895,9 @@ 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; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_name) { + // named parameter with possible annotation param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); if (comp->have_star) { // comes after a star, so counts as a keyword-only parameter @@ -2788,19 +2917,22 @@ 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); + pns = NULL; } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])) { // named star comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS; param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); + pns = NULL; } else { 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 { + // double star with possible annotation assert(MP_PARSE_NODE_STRUCT_KIND(pns) == pn_dbl_star); // should be param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); param_flag = ID_FLAG_IS_PARAM | ID_FLAG_IS_DBL_STAR_PARAM; @@ -2809,14 +2941,21 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn } if (param_name != MP_QSTR_NULL) { - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, param_name, &added); - if (!added) { + id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, param_name, ID_INFO_KIND_UNDECIDED); + if (id_info->kind != ID_INFO_KIND_UNDECIDED) { compile_syntax_error(comp, pn, translate("name reused for argument")); return; } id_info->kind = ID_INFO_KIND_LOCAL; id_info->flags = param_flag; + + #if MICROPY_EMIT_NATIVE + if (comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER && pn_name == PN_typedargslist_name && pns != NULL) { + id_info->flags |= compile_viper_type_annotation(comp, pns->nodes[1]) << ID_FLAG_VIPER_TYPE_POS; + } + #else + (void)pns; + #endif } } @@ -2828,49 +2967,6 @@ STATIC void compile_scope_lambda_param(compiler_t *comp, mp_parse_node_t pn) { compile_scope_func_lambda_param(comp, pn, PN_varargslist_name, PN_varargslist_star, PN_varargslist_dbl_star); } -#if MICROPY_EMIT_NATIVE -STATIC void compile_scope_func_annotations(compiler_t *comp, mp_parse_node_t pn) { - if (!MP_PARSE_NODE_IS_STRUCT(pn)) { - // no annotation - return; - } - - 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]; - // fallthrough - } else { - // no annotation - return; - } - } else { - assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_dbl_star); - // double star with possible annotation - // fallthrough - } - - mp_parse_node_t pn_annotation = pns->nodes[1]; - - if (!MP_PARSE_NODE_IS_NULL(pn_annotation)) { - qstr param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); - id_info_t *id_info = scope_find(comp->scope_cur, param_name); - assert(id_info != NULL); - - if (MP_PARSE_NODE_IS_ID(pn_annotation)) { - qstr arg_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_ARG, id_info->local_num, arg_type); - } else { - compile_syntax_error(comp, pn_annotation, translate("parameter annotation must be an identifier")); - } - } -} -#endif // MICROPY_EMIT_NATIVE - STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pns_comp_for, mp_parse_node_t pn_inner_expr, int for_depth) { uint l_top = comp_next_label(comp); uint l_end = comp_next_label(comp); @@ -2879,26 +2975,27 @@ 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); if (comp->scope_cur->kind == SCOPE_GEN_EXPR) { EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); + reserve_labels_for_native(comp, 1); EMIT(pop_top); } 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 +3007,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 +3015,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 +3027,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) { @@ -2959,6 +3056,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { comp->scope_cur = scope; comp->next_label = 0; EMIT_ARG(start_pass, pass, scope); + reserve_labels_for_native(comp, 6); // used by native's start_pass if (comp->pass == MP_PASS_SCOPE) { // reset maximum stack sizes in scope @@ -2970,7 +3068,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 +3080,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 @@ -2990,28 +3088,14 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { if (comp->pass == MP_PASS_SCOPE) { comp->have_star = false; apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_scope_func_param); - } - #if MICROPY_EMIT_NATIVE - else if (scope->emit_options == MP_EMIT_OPT_VIPER) { - // compile annotations; only needed on latter compiler passes - // only needed for viper emitter - - // argument annotations - apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_scope_func_annotations); - - // pns->nodes[2] is return/whole function annotation - mp_parse_node_t pn_annotation = pns->nodes[2]; - if (!MP_PARSE_NODE_IS_NULL(pn_annotation)) { - // nodes[2] can be null or a test-expr - if (MP_PARSE_NODE_IS_ID(pn_annotation)) { - qstr ret_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); - EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_RETURN, 0, ret_type); - } else { - compile_syntax_error(comp, pn_annotation, translate("return annotation must be an identifier")); - } + + #if MICROPY_EMIT_NATIVE + if (scope->emit_options == MP_EMIT_OPT_VIPER) { + // Compile return type; pns->nodes[2] is return/whole function annotation + scope->scope_flags |= compile_viper_type_annotation(comp, pns->nodes[2]) << MP_SCOPE_FLAG_VIPERRET_POS; } + #endif // MICROPY_EMIT_NATIVE } - #endif // MICROPY_EMIT_NATIVE compile_node(comp, pns->nodes[3]); // 3 is function body // emit return if it wasn't the last opcode @@ -3021,7 +3105,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 +3127,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 @@ -3054,10 +3138,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { // so we use the blank qstr. qstr qstr_arg = MP_QSTR_; if (comp->pass == MP_PASS_SCOPE) { - bool added; - id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qstr_arg, &added); - assert(added); - id_info->kind = ID_INFO_KIND_LOCAL; + scope_find_or_add_id(comp->scope_cur, qstr_arg, ID_INFO_KIND_LOCAL); scope->num_pos_args = 1; } @@ -3093,14 +3174,11 @@ 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) { - bool added; - id_info_t *id_info = scope_find_or_add_id(scope, MP_QSTR___class__, &added); - assert(added); - id_info->kind = ID_INFO_KIND_LOCAL; + scope_find_or_add_id(scope, MP_QSTR___class__, ID_INFO_KIND_LOCAL); } compile_load_id(comp, MP_QSTR___name__); @@ -3145,10 +3223,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 +3246,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 +3273,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 +3289,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 +3303,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 +3326,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 +3341,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 +3361,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 +3385,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) { @@ -3318,6 +3408,17 @@ STATIC void scope_compute_things(scope_t *scope) { if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { id->kind = ID_INFO_KIND_GLOBAL_EXPLICIT; } + #if MICROPY_EMIT_NATIVE + if (id->kind == ID_INFO_KIND_GLOBAL_EXPLICIT) { + // This function makes a reference to a global variable + if (scope->emit_options == MP_EMIT_OPT_VIPER + && mp_native_type_from_qstr(id->qst) >= MP_NATIVE_TYPE_INT) { + // A casting operator in viper mode, not a real global reference + } else { + scope->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS; + } + } + #endif // params always count for 1 local, even if they are a cell if (id->kind == ID_INFO_KIND_LOCAL || (id->flags & ID_FLAG_IS_PARAM)) { id->local_num = scope->num_locals++; @@ -3401,6 +3502,14 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f #endif } else { compile_scope(comp, s, MP_PASS_SCOPE); + + // Check if any implicitly declared variables should be closed over + for (size_t i = 0; i < s->id_info_len; ++i) { + id_info_t *id = &s->id_info[i]; + if (id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { + scope_check_to_close_over(s, id); + } + } } // update maximim number of labels needed @@ -3418,9 +3527,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,17 +3560,16 @@ 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) { - emit_native = NATIVE_EMITTER(new)(&comp->compile_error, max_num_labels); + emit_native = NATIVE_EMITTER(new)(&comp->compile_error, &comp->next_label, max_num_labels); } comp->emit_method_table = &NATIVE_EMITTER(method_table); 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 +3606,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/compile.h b/py/compile.h index 0f8d023a25c3b..b9c0c653fa7a8 100644 --- a/py/compile.h +++ b/py/compile.h @@ -30,15 +30,6 @@ #include "py/parse.h" #include "py/emitglue.h" -// These must fit in 8 bits; see scope.h -enum { - MP_EMIT_OPT_NONE, - MP_EMIT_OPT_BYTECODE, - MP_EMIT_OPT_NATIVE_PYTHON, - MP_EMIT_OPT_VIPER, - MP_EMIT_OPT_ASM, -}; - // the compiler will raise an exception if an error occurred // the compiler will clear the parse tree before it returns mp_obj_t mp_compile(mp_parse_tree_t *parse_tree, qstr source_file, uint emit_opt, bool is_repl); diff --git a/py/emit.h b/py/emit.h index 30543d2a3c289..24a31f8e234bb 100644 --- a/py/emit.h +++ b/py/emit.h @@ -51,10 +51,6 @@ typedef enum { #define MP_EMIT_BREAK_FROM_FOR (0x8000) -#define MP_EMIT_NATIVE_TYPE_ENABLE (0) -#define MP_EMIT_NATIVE_TYPE_RETURN (1) -#define MP_EMIT_NATIVE_TYPE_ARG (2) - // Kind for emit_id_ops->local() #define MP_EMIT_IDOP_LOCAL_FAST (0) #define MP_EMIT_IDOP_LOCAL_DEREF (1) @@ -102,7 +98,6 @@ typedef struct _mp_emit_method_table_id_ops_t { } mp_emit_method_table_id_ops_t; typedef struct _emit_method_table_t { - void (*set_native_type)(emit_t *emit, mp_uint_t op, mp_uint_t arg1, qstr arg2); void (*start_pass)(emit_t *emit, pass_kind_t pass, scope_t *scope); void (*end_pass)(emit_t *emit); bool (*last_emit_was_return_value)(emit_t *emit); @@ -162,7 +157,12 @@ typedef struct _emit_method_table_t { void (*end_except_handler)(emit_t *emit); } emit_method_table_t; -void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst); +int mp_native_type_from_qstr(qstr qst); + +static inline void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst) { + scope_find_or_add_id(scope, qst, ID_INFO_KIND_GLOBAL_IMPLICIT); +} + void mp_emit_common_get_id_for_modification(scope_t *scope, qstr qst); void mp_emit_common_id_op(emit_t *emit, const mp_emit_method_table_id_ops_t *emit_method_table, scope_t *scope, qstr qst); @@ -178,13 +178,13 @@ extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_store_id_ops; extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_delete_id_ops; emit_t *emit_bc_new(void); -emit_t *emit_native_x64_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -emit_t *emit_native_x86_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -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); +emit_t *emit_native_x64_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_x86_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_thumb_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_arm_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, uint *label_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 f45dcb9167566..7e2989276f894 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 } @@ -331,6 +331,10 @@ void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { // the highest slot in the state (fastn[0], see vm.c). n_state = 1; } + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + // An extra slot in the stack is needed to detect VM stack overflow + n_state += 1; + #endif emit_write_code_info_uint(emit, n_state); emit_write_code_info_uint(emit, scope->exc_stack_size); } @@ -347,7 +351,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 +473,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 +486,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 +526,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 +734,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); @@ -910,7 +920,6 @@ void mp_emit_bc_end_except_handler(emit_t *emit) { #if MICROPY_EMIT_NATIVE const emit_method_table_t emit_bc_method_table = { - NULL, // set_native_type is never called when emitting bytecode mp_emit_bc_start_pass, mp_emit_bc_end_pass, mp_emit_bc_last_emit_was_return_value, @@ -993,4 +1002,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/emitcommon.c b/py/emitcommon.c index 88c9803a6e2e7..177418c30ab64 100644 --- a/py/emitcommon.c +++ b/py/emitcommon.c @@ -30,26 +30,10 @@ #if MICROPY_ENABLE_COMPILER -void mp_emit_common_get_id_for_load(scope_t *scope, qstr qst) { - // name adding/lookup - bool added; - id_info_t *id = scope_find_or_add_id(scope, qst, &added); - if (added) { - scope_find_local_and_close_over(scope, id, qst); - } -} - void mp_emit_common_get_id_for_modification(scope_t *scope, qstr qst) { // name adding/lookup - bool added; - id_info_t *id = scope_find_or_add_id(scope, qst, &added); - if (added) { - if (SCOPE_IS_FUNC_LIKE(scope->kind)) { - id->kind = ID_INFO_KIND_LOCAL; - } else { - id->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; - } - } else if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { + id_info_t *id = scope_find_or_add_id(scope, qst, ID_INFO_KIND_GLOBAL_IMPLICIT); + if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) { // rebind as a local variable id->kind = ID_INFO_KIND_LOCAL; } diff --git a/py/emitglue.c b/py/emitglue.c index 7635a73d6a7ba..4949053410703 100644 --- a/py/emitglue.c +++ b/py/emitglue.c @@ -75,14 +75,17 @@ 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 + #if !MICROPY_DEBUG_PRINTERS + const size_t len = 0; + #endif 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 +98,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 @@ -131,10 +134,8 @@ mp_obj_t mp_make_function_from_raw_code(const mp_raw_code_t *rc, mp_obj_t def_ar switch (rc->kind) { #if MICROPY_EMIT_NATIVE case MP_CODE_NATIVE_PY: - fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->data.u_native.fun_data, rc->data.u_native.const_table); - break; case MP_CODE_NATIVE_VIPER: - fun = mp_obj_new_fun_viper(rc->n_pos_args, rc->data.u_native.fun_data, rc->data.u_native.type_sig); + fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->data.u_native.fun_data, rc->data.u_native.const_table); break; #endif #if MICROPY_EMIT_INLINE_ASM diff --git a/py/emitglue.h b/py/emitglue.h index 2ddcc3e53ef99..fc352fdbab547 100644 --- a/py/emitglue.h +++ b/py/emitglue.h @@ -30,6 +30,15 @@ // These variables and functions glue the code emitters to the runtime. +// These must fit in 8 bits; see scope.h +enum { + MP_EMIT_OPT_NONE, + MP_EMIT_OPT_BYTECODE, + MP_EMIT_OPT_NATIVE_PYTHON, + MP_EMIT_OPT_VIPER, + MP_EMIT_OPT_ASM, +}; + typedef enum { MP_CODE_UNUSED, MP_CODE_RESERVED, diff --git a/py/emitinlinethumb.c b/py/emitinlinethumb.c index 47ed14321ec36..1faeccbd2792b 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 ae84aae2e3238..8094c0befaea1 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/emitnarm.c b/py/emitnarm.c index 1b585f821b4a6..8297ad61921a8 100644 --- a/py/emitnarm.c +++ b/py/emitnarm.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmarm.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (3) // r4 +#define NLR_BUF_IDX_LOCAL_2 (4) // r5 +#define NLR_BUF_IDX_LOCAL_3 (5) // r6 + #define N_ARM (1) #define EXPORT_FUN(name) emit_native_arm_##name #include "py/emitnative.c" diff --git a/py/emitnative.c b/py/emitnative.c index 51919e389b327..bcf7793c8681a 100644 --- a/py/emitnative.c +++ b/py/emitnative.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -49,8 +49,6 @@ #include "py/emit.h" #include "py/bc.h" -#include "supervisor/shared/translate.h" - #if MICROPY_DEBUG_VERBOSE // print debugging info #define DEBUG_PRINT (1) #define DEBUG_printf DEBUG_printf @@ -59,34 +57,80 @@ #endif #ifndef N_X64 - #define N_X64 (0) +#define N_X64 (0) #endif + #ifndef N_X86 - #define N_X86 (0) +#define N_X86 (0) #endif + #ifndef N_THUMB - #define N_THUMB (0) +#define N_THUMB (0) #endif + #ifndef N_ARM - #define N_ARM (0) +#define N_ARM (0) #endif + #ifndef N_XTENSA - #define N_XTENSA (0) +#define N_XTENSA (0) #endif // wrapper around everything in this file #if N_X64 || N_X86 || N_THUMB || N_ARM || N_XTENSA -// define additional generic helper macros -#define ASM_MOV_LOCAL_IMM_VIA(as, local_num, imm, reg_temp) \ - do { \ - ASM_MOV_REG_IMM((as), (reg_temp), (imm)); \ - ASM_MOV_LOCAL_REG((as), (local_num), (reg_temp)); \ - } while (false) +// C stack layout for native functions: +// 0: nlr_buf_t [optional] +// emit->code_state_start: mp_code_state_t +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// +// C stack layout for native generator functions: +// 0=emit->stack_start: nlr_buf_t +// +// Then REG_GENERATOR_STATE points to: +// 0=emit->code_state_start: mp_code_state_t +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// +// C stack layout for viper functions: +// 0: nlr_buf_t [optional] +// emit->code_state_start: fun_obj, old_globals [optional] +// emit->stack_start: Python object stack | emit->n_state +// locals (reversed, L0 at end) | +// (L0-L2 may be in regs instead) + +// Word index of nlr_buf_t.ret_val +#define NLR_BUF_IDX_RET_VAL (1) + +// Whether the viper function needs access to fun_obj +#define NEED_FUN_OBJ(emit) ((emit)->scope->exc_stack_size > 0 \ + || ((emit)->scope->scope_flags & (MP_SCOPE_FLAG_REFGLOBALS | MP_SCOPE_FLAG_HASCONSTS))) + +// Whether the native/viper function needs to be wrapped in an exception handler +#define NEED_GLOBAL_EXC_HANDLER(emit) ((emit)->scope->exc_stack_size > 0 \ + || ((emit)->scope->scope_flags & (MP_SCOPE_FLAG_GENERATOR | MP_SCOPE_FLAG_REFGLOBALS))) + +// Whether registers can be used to store locals (only true if there are no +// exception handlers, because otherwise an nlr_jump will restore registers to +// their state at the start of the function and updates to locals will be lost) +#define CAN_USE_REGS_FOR_LOCALS(emit) ((emit)->scope->exc_stack_size == 0 && !(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) + +// Indices within the local C stack for various variables +#define LOCAL_IDX_EXC_VAL(emit) (NLR_BUF_IDX_RET_VAL) +#define LOCAL_IDX_EXC_HANDLER_PC(emit) (NLR_BUF_IDX_LOCAL_1) +#define LOCAL_IDX_EXC_HANDLER_UNWIND(emit) (NLR_BUF_IDX_LOCAL_2) +#define LOCAL_IDX_RET_VAL(emit) (NLR_BUF_IDX_LOCAL_3) +#define LOCAL_IDX_FUN_OBJ(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, fun_bc) / sizeof(uintptr_t)) +#define LOCAL_IDX_OLD_GLOBALS(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t)) +#define LOCAL_IDX_GEN_PC(emit) ((emit)->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t)) +#define LOCAL_IDX_LOCAL_VAR(emit, local_num) ((emit)->stack_start + (emit)->n_state - 1 - (local_num)) + +#define REG_GENERATOR_STATE (REG_LOCAL_3) #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, @@ -112,17 +156,50 @@ typedef enum { VTYPE_BUILTIN_CAST = 0x70 | MP_NATIVE_TYPE_OBJ, } vtype_kind_t; +int mp_native_type_from_qstr(qstr qst) { + switch (qst) { + case MP_QSTR_object: + return MP_NATIVE_TYPE_OBJ; + case MP_QSTR_bool: + return MP_NATIVE_TYPE_BOOL; + case MP_QSTR_int: + return MP_NATIVE_TYPE_INT; + case MP_QSTR_uint: + return MP_NATIVE_TYPE_UINT; + case MP_QSTR_ptr: + return MP_NATIVE_TYPE_PTR; + case MP_QSTR_ptr8: + return MP_NATIVE_TYPE_PTR8; + case MP_QSTR_ptr16: + return MP_NATIVE_TYPE_PTR16; + case MP_QSTR_ptr32: + return MP_NATIVE_TYPE_PTR32; + default: + return -1; + } +} + 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; } } @@ -135,14 +212,24 @@ typedef struct _stack_info_t { } data; } stack_info_t; +#define UNWIND_LABEL_UNUSED (0x7fff) +#define UNWIND_LABEL_DO_FINAL_UNWIND (0x7ffe) + +typedef struct _exc_stack_entry_t { + uint16_t label : 15; + uint16_t is_finally : 1; + uint16_t unwind_label : 15; + uint16_t is_active : 1; +} exc_stack_entry_t; + struct _emit_t { mp_obj_t *error_slot; + uint *label_slot; + uint exit_label; int pass; bool do_viper_types; - vtype_kind_t return_vtype; - mp_uint_t local_vtype_alloc; vtype_kind_t *local_vtype; @@ -150,12 +237,22 @@ struct _emit_t { stack_info_t *stack_info; vtype_kind_t saved_stack_vtype; + size_t exc_stack_alloc; + size_t exc_stack_size; + exc_stack_entry_t *exc_stack; + int prelude_offset; - int const_table_offset; + int start_offset; int n_state; - int stack_start; + uint16_t code_state_start; + uint16_t stack_start; int stack_size; + uint16_t const_table_cur_obj; + uint16_t const_table_num_obj; + uint16_t const_table_cur_raw_code; + mp_uint_t *const_table; + bool last_emit_was_return_value; scope_t *scope; @@ -163,65 +260,78 @@ struct _emit_t { ASM_T *as; }; -emit_t *EXPORT_FUN(new)(mp_obj_t *error_slot, mp_uint_t max_num_labels) { +STATIC const uint8_t reg_local_table[REG_LOCAL_NUM] = {REG_LOCAL_1, REG_LOCAL_2, REG_LOCAL_3}; + +STATIC void emit_native_global_exc_entry(emit_t *emit); +STATIC void emit_native_global_exc_exit(emit_t *emit); + +emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, uint *label_slot, mp_uint_t max_num_labels) { emit_t *emit = m_new0(emit_t, 1); emit->error_slot = error_slot; + emit->label_slot = label_slot; + emit->stack_info_alloc = 8; + emit->stack_info = m_new(stack_info_t, emit->stack_info_alloc); + emit->exc_stack_alloc = 8; + emit->exc_stack = m_new(exc_stack_entry_t, emit->exc_stack_alloc); emit->as = m_new0(ASM_T, 1); mp_asm_base_init(&emit->as->base, 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(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc); m_del(vtype_kind_t, emit->local_vtype, emit->local_vtype_alloc); m_del(stack_info_t, emit->stack_info, emit->stack_info_alloc); m_del_obj(emit_t, emit); } -STATIC void emit_native_set_native_type(emit_t *emit, mp_uint_t op, mp_uint_t arg1, qstr arg2) { - switch (op) { - case MP_EMIT_NATIVE_TYPE_ENABLE: - emit->do_viper_types = arg1; - break; +STATIC void emit_call_with_imm_arg(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg); - 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; - } - if (op == MP_EMIT_NATIVE_TYPE_RETURN) { - emit->return_vtype = type; - } else { - assert(arg1 < emit->local_vtype_alloc); - emit->local_vtype[arg1] = type; - } - break; - } +STATIC void emit_native_mov_reg_const(emit_t *emit, int reg_dest, int const_val) { + ASM_LOAD_REG_REG_OFFSET(emit->as, reg_dest, REG_FUN_TABLE, const_val); +} + +STATIC void emit_native_mov_state_reg(emit_t *emit, int local_num, int reg_src) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_STORE_REG_REG_OFFSET(emit->as, reg_src, REG_GENERATOR_STATE, local_num); + } else { + ASM_MOV_LOCAL_REG(emit->as, local_num, reg_src); } } -STATIC void emit_pre_pop_reg(emit_t *emit, vtype_kind_t *vtype, int reg_dest); -STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg); -STATIC void emit_native_load_fast(emit_t *emit, qstr qst, mp_uint_t local_num); -STATIC void emit_native_store_fast(emit_t *emit, qstr qst, mp_uint_t local_num); +STATIC void emit_native_mov_reg_state(emit_t *emit, int reg_dest, int local_num) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_LOAD_REG_REG_OFFSET(emit->as, reg_dest, REG_GENERATOR_STATE, local_num); + } else { + ASM_MOV_REG_LOCAL(emit->as, reg_dest, local_num); + } +} -#define STATE_START (sizeof(mp_code_state_t) / sizeof(mp_uint_t)) +STATIC void emit_native_mov_reg_state_addr(emit_t *emit, int reg_dest, int local_num) { + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + ASM_MOV_REG_IMM(emit->as, reg_dest, local_num * ASM_WORD_SIZE); + ASM_ADD_REG_REG(emit->as, reg_dest, REG_GENERATOR_STATE); + } else { + ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, local_num); + } +} + +#define emit_native_mov_state_imm_via(emit, local_num, imm, reg_temp) \ + do { \ + ASM_MOV_REG_IMM((emit)->as, (reg_temp), (imm)); \ + emit_native_mov_state_reg((emit), (local_num), (reg_temp)); \ + } while (false) STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { DEBUG_printf("start_pass(pass=%u, scope=%p)\n", pass, scope); emit->pass = pass; - emit->stack_start = 0; + emit->do_viper_types = scope->emit_options == MP_EMIT_OPT_VIPER; emit->stack_size = 0; + emit->const_table_cur_obj = 1; // first entry is for mp_fun_table + emit->const_table_cur_raw_code = 0; emit->last_emit_was_return_value = false; emit->scope = scope; @@ -231,17 +341,6 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype_alloc = scope->num_locals; } - // allocate memory for keeping track of the objects on the stack - // XXX don't know stack size on entry, and it should be maximum over all scopes - // XXX this is such a big hack and really needs to be fixed - if (emit->stack_info == NULL) { - emit->stack_info_alloc = scope->stack_size + 200; - emit->stack_info = m_new(stack_info_t, emit->stack_info_alloc); - } - - // set default type for return - emit->return_vtype = VTYPE_PYOBJ; - // set default type for arguments mp_uint_t num_args = emit->scope->num_pos_args + emit->scope->num_kwonly_args; if (scope->scope_flags & MP_SCOPE_FLAG_VARARGS) { @@ -254,6 +353,17 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype[i] = VTYPE_PYOBJ; } + // Set viper type for arguments + if (emit->do_viper_types) { + for (int i = 0; i < emit->scope->id_info_len; ++i) { + id_info_t *id = &emit->scope->id_info[i]; + if (id->flags & ID_FLAG_IS_PARAM) { + assert(id->local_num < emit->local_vtype_alloc); + emit->local_vtype[id->local_num] = id->flags >> ID_FLAG_VIPER_TYPE_POS; + } + } + } + // local variables begin unbound, and have unknown type for (mp_uint_t i = num_args; i < emit->local_vtype_alloc; i++) { emit->local_vtype[i] = VTYPE_UNBOUND; @@ -269,111 +379,171 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop // generate code for entry to function - if (emit->do_viper_types) { + // Work out start of code state (mp_code_state_t or reduced version for viper) + emit->code_state_start = 0; + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + emit->code_state_start = sizeof(nlr_buf_t) / sizeof(uintptr_t); + } - // right now we have a restriction of maximum of 4 arguments - if (scope->num_pos_args >= 5) { - EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("Viper functions don't currently support more than 4 arguments")); - return; + if (emit->do_viper_types) { + // Work out size of state (locals plus stack) + // n_state counts all stack and locals, even those in registers + emit->n_state = scope->num_locals + scope->stack_size; + int num_locals_in_regs = 0; + if (CAN_USE_REGS_FOR_LOCALS(emit)) { + num_locals_in_regs = scope->num_locals; + if (num_locals_in_regs > REG_LOCAL_NUM) { + num_locals_in_regs = REG_LOCAL_NUM; + } + // Need a spot for REG_LOCAL_3 if 4 or more args (see below) + if (scope->num_pos_args >= 4) { + --num_locals_in_regs; + } } - // entry to function - int num_locals = 0; - if (pass > MP_PASS_SCOPE) { - num_locals = scope->num_locals - REG_LOCAL_NUM; - if (num_locals < 0) { - num_locals = 0; - } - emit->stack_start = num_locals; - num_locals += scope->stack_size; + // Work out where the locals and Python stack start within the C stack + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Reserve 2 words for function object and old globals + emit->stack_start = emit->code_state_start + 2; + } else if (scope->scope_flags & MP_SCOPE_FLAG_HASCONSTS) { + // Reserve 1 word for function object, to access const table + emit->stack_start = emit->code_state_start + 1; + } else { + emit->stack_start = emit->code_state_start + 0; } - ASM_ENTRY(emit->as, num_locals); - // TODO don't load r7 if we don't need it - #if N_THUMB - asm_thumb_mov_reg_i32(emit->as, ASM_THUMB_REG_R7, (mp_uint_t)mp_fun_table); - #elif N_ARM - asm_arm_mov_reg_i32(emit->as, ASM_ARM_REG_R7, (mp_uint_t)mp_fun_table); - #endif + // Entry to function + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state - num_locals_in_regs); #if N_X86 - for (int i = 0; i < scope->num_pos_args; i++) { - if (i == 0) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_1); - } else if (i == 1) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_2); - } else if (i == 2) { - asm_x86_mov_arg_to_r32(emit->as, i, REG_LOCAL_3); - } else { - asm_x86_mov_arg_to_r32(emit->as, i, REG_TEMP0); - asm_x86_mov_r32_to_local(emit->as, REG_TEMP0, i - REG_LOCAL_NUM); - } + asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); + #endif + + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_LOCAL_3, REG_ARG_1, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_LOCAL_3, 0); + + // Store function object (passed as first arg) to stack if needed + if (NEED_FUN_OBJ(emit)) { + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_FUN_OBJ(emit), REG_ARG_1); } + + // Put n_args in REG_ARG_1, n_kw in REG_ARG_2, args array in REG_LOCAL_3 + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_1); + asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_2); + asm_x86_mov_arg_to_r32(emit->as, 3, REG_LOCAL_3); #else - for (int i = 0; i < scope->num_pos_args; i++) { - if (i == 0) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_1, REG_ARG_1); - } else if (i == 1) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_2, REG_ARG_2); - } else if (i == 2) { - ASM_MOV_REG_REG(emit->as, REG_LOCAL_3, REG_ARG_3); + ASM_MOV_REG_REG(emit->as, REG_ARG_1, REG_ARG_2); + ASM_MOV_REG_REG(emit->as, REG_ARG_2, REG_ARG_3); + ASM_MOV_REG_REG(emit->as, REG_LOCAL_3, REG_ARG_4); + #endif + + // Check number of args matches this function, and call mp_arg_check_num_sig if not + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_ARG_2, *emit->label_slot + 4, true); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, scope->num_pos_args); + ASM_JUMP_IF_REG_EQ(emit->as, REG_ARG_1, REG_ARG_3, *emit->label_slot + 5); + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot + 4); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, MP_OBJ_FUN_MAKE_SIG(scope->num_pos_args, scope->num_pos_args, false)); + ASM_CALL_IND(emit->as, MP_F_ARG_CHECK_NUM_SIG); + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot + 5); + + // Store arguments into locals (reg or stack), converting to native if needed + for (int i = 0; i < emit->scope->num_pos_args; i++) { + int r = REG_ARG_1; + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_1, REG_LOCAL_3, i); + if (emit->local_vtype[i] != VTYPE_PYOBJ) { + emit_call_with_imm_arg(emit, MP_F_CONVERT_OBJ_TO_NATIVE, emit->local_vtype[i], REG_ARG_2); + r = REG_RET; + } + // REG_LOCAL_3 points to the args array so be sure not to overwrite it if it's still needed + if (i < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit) && (i != 2 || emit->scope->num_pos_args == 3)) { + ASM_MOV_REG_REG(emit->as, reg_local_table[i], r); } else { - assert(i == 3); // should be true; max 4 args is checked above - ASM_MOV_LOCAL_REG(emit->as, i - REG_LOCAL_NUM, REG_ARG_4); + emit_native_mov_state_reg(emit, LOCAL_IDX_LOCAL_VAR(emit, i), r); } } - #endif + // Get 3rd local from the stack back into REG_LOCAL_3 if this reg couldn't be written to above + if (emit->scope->num_pos_args >= 4 && CAN_USE_REGS_FOR_LOCALS(emit)) { + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_3, LOCAL_IDX_LOCAL_VAR(emit, 2)); + } + + emit_native_global_exc_entry(emit); } else { // work out size of state (locals plus stack) emit->n_state = scope->num_locals + scope->stack_size; - // allocate space on C-stack for code_state structure, which includes state - ASM_ENTRY(emit->as, STATE_START + emit->n_state); + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + emit->code_state_start = 0; + emit->stack_start = sizeof(mp_code_state_t) / sizeof(mp_uint_t); + mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (uintptr_t)emit->prelude_offset); + mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (uintptr_t)emit->start_offset); + ASM_ENTRY(emit->as, sizeof(nlr_buf_t) / sizeof(uintptr_t)); - // TODO don't load r7 if we don't need it - #if N_THUMB - asm_thumb_mov_reg_i32(emit->as, ASM_THUMB_REG_R7, (mp_uint_t)mp_fun_table); - #elif N_ARM - asm_arm_mov_reg_i32(emit->as, ASM_ARM_REG_R7, (mp_uint_t)mp_fun_table); - #endif + // Put address of code_state into REG_GENERATOR_STATE + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 0, REG_GENERATOR_STATE); + #else + ASM_MOV_REG_REG(emit->as, REG_GENERATOR_STATE, REG_ARG_1); + #endif - // prepare incoming arguments for call to mp_setup_code_state + // Put throw value into LOCAL_IDX_EXC_VAL slot, for yield/yield-from + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); + #endif + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_ARG_2); - #if N_X86 - asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); - asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); - asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_3); - asm_x86_mov_arg_to_r32(emit->as, 3, REG_ARG_4); - #endif + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_GENERATOR_STATE, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_TEMP0, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_TEMP0, emit->scope->num_pos_args + emit->scope->num_kwonly_args); + } else { + // The locals and stack start after the code_state structure + emit->stack_start = emit->code_state_start + sizeof(mp_code_state_t) / sizeof(mp_uint_t); + + // Allocate space on C-stack for code_state structure, which includes state + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state); - // set code_state.fun_bc - ASM_MOV_LOCAL_REG(emit->as, offsetof(mp_code_state_t, fun_bc) / sizeof(uintptr_t), REG_ARG_1); + // Prepare incoming arguments for call to mp_setup_code_state - // set code_state.ip (offset from start of this function to prelude info) - // XXX this encoding may change size - ASM_MOV_LOCAL_IMM_VIA(emit->as, offsetof(mp_code_state_t, ip) / sizeof(uintptr_t), emit->prelude_offset, REG_ARG_1); + #if N_X86 + asm_x86_mov_arg_to_r32(emit->as, 0, REG_ARG_1); + asm_x86_mov_arg_to_r32(emit->as, 1, REG_ARG_2); + asm_x86_mov_arg_to_r32(emit->as, 2, REG_ARG_3); + asm_x86_mov_arg_to_r32(emit->as, 3, REG_ARG_4); + #endif - // put address of code_state into first arg - ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + // Load REG_FUN_TABLE with a pointer to mp_fun_table, found in the const_table + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_LOCAL_3, REG_ARG_1, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_FUN_TABLE, REG_LOCAL_3, emit->scope->num_pos_args + emit->scope->num_kwonly_args); - // call mp_setup_code_state to prepare code_state structure - #if N_THUMB - asm_thumb_bl_ind(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE, ASM_THUMB_REG_R4); - #elif N_ARM - asm_arm_bl_ind(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE, ASM_ARM_REG_R4); - #else - ASM_CALL_IND(emit->as, mp_fun_table[MP_F_SETUP_CODE_STATE], MP_F_SETUP_CODE_STATE); - #endif + // Set code_state.fun_bc + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_FUN_OBJ(emit), REG_ARG_1); - // cache some locals in registers - if (scope->num_locals > 0) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_1, STATE_START + emit->n_state - 1 - 0); - if (scope->num_locals > 1) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_2, STATE_START + emit->n_state - 1 - 1); - if (scope->num_locals > 2) { - ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_3, STATE_START + emit->n_state - 1 - 2); - } + // Set code_state.ip (offset from start of this function to prelude info) + // TODO this encoding may change size in the final pass, need to make it fixed + emit_native_mov_state_imm_via(emit, emit->code_state_start + offsetof(mp_code_state_t, ip) / sizeof(uintptr_t), emit->prelude_offset, REG_ARG_1); + + // Put address of code_state into first arg + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, emit->code_state_start); + + // Call mp_setup_code_state to prepare code_state structure + #if N_THUMB + asm_thumb_bl_ind(emit->as, MP_F_SETUP_CODE_STATE, ASM_THUMB_REG_R4); + #elif N_ARM + asm_arm_bl_ind(emit->as, MP_F_SETUP_CODE_STATE, ASM_ARM_REG_R4); + #else + ASM_CALL_IND(emit->as, MP_F_SETUP_CODE_STATE); + #endif + } + + emit_native_global_exc_entry(emit); + + // cache some locals in registers, but only if no exception handlers + if (CAN_USE_REGS_FOR_LOCALS(emit)) { + for (int i = 0; i < REG_LOCAL_NUM && i < scope->num_locals; ++i) { + ASM_MOV_REG_LOCAL(emit->as, reg_local_table[i], LOCAL_IDX_LOCAL_VAR(emit, i)); } } @@ -384,14 +554,28 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->local_vtype[id->local_num] = VTYPE_PYOBJ; } } + + if (pass == MP_PASS_EMIT) { + // write argument names as qstr objects + // see comment in corresponding part of emitbc.c about the logic here + for (int i = 0; i < scope->num_pos_args + scope->num_kwonly_args; i++) { + qstr qst = MP_QSTR__star_; + for (int j = 0; j < scope->id_info_len; ++j) { + id_info_t *id = &scope->id_info[j]; + if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) { + qst = id->qst; + break; + } + } + emit->const_table[i] = (mp_uint_t)MP_OBJ_NEW_QSTR(qst); + } + } } } STATIC void emit_native_end_pass(emit_t *emit) { - if (!emit->last_emit_was_return_value) { - ASM_EXIT(emit->as); - } + emit_native_global_exc_exit(emit); if (!emit->do_viper_types) { emit->prelude_offset = mp_asm_base_get_code_pos(&emit->as->base); @@ -423,49 +607,38 @@ STATIC void emit_native_end_pass(emit_t *emit) { } } mp_asm_base_data(&emit->as->base, 1, 255); // end of list sentinel - - mp_asm_base_align(&emit->as->base, ASM_WORD_SIZE); - emit->const_table_offset = mp_asm_base_get_code_pos(&emit->as->base); - - // write argument names as qstr objects - // see comment in corresponding part of emitbc.c about the logic here - for (int i = 0; i < emit->scope->num_pos_args + emit->scope->num_kwonly_args; i++) { - qstr qst = MP_QSTR__star_; - for (int j = 0; j < emit->scope->id_info_len; ++j) { - id_info_t *id = &emit->scope->id_info[j]; - if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) { - qst = id->qst; - break; - } - } - mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (mp_uint_t)MP_OBJ_NEW_QSTR(qst)); - } - } ASM_END_PASS(emit->as); // check stack is back to zero size assert(emit->stack_size == 0); + assert(emit->exc_stack_size == 0); + + // Deal with const table accounting + assert(emit->pass <= MP_PASS_STACK_SIZE || (emit->const_table_num_obj == emit->const_table_cur_obj)); + emit->const_table_num_obj = emit->const_table_cur_obj; + if (emit->pass == MP_PASS_CODE_SIZE) { + size_t const_table_alloc = emit->const_table_num_obj + emit->const_table_cur_raw_code; + size_t nqstr = 0; + if (!emit->do_viper_types) { + // Add room for qstr names of arguments + nqstr = emit->scope->num_pos_args + emit->scope->num_kwonly_args; + const_table_alloc += nqstr; + } + emit->const_table = m_new(mp_uint_t, const_table_alloc); + // Store mp_fun_table pointer just after qstrs + emit->const_table[nqstr] = (mp_uint_t)(uintptr_t)mp_fun_table; + } if (emit->pass == MP_PASS_EMIT) { void *f = mp_asm_base_get_code(&emit->as->base); mp_uint_t f_len = mp_asm_base_get_code_size(&emit->as->base); - // compute type signature - // note that the lower 4 bits of a vtype are tho correct MP_NATIVE_TYPE_xxx - mp_uint_t type_sig = emit->return_vtype & 0xf; - for (mp_uint_t i = 0; i < emit->scope->num_pos_args; i++) { - type_sig |= (emit->local_vtype[i] & 0xf) << (i * 4 + 4); - } - - #pragma GCC diagnostic push - #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), - emit->scope->num_pos_args, emit->scope->scope_flags, type_sig); - #pragma GCC diagnostic pop + f, f_len, emit->const_table, + emit->scope->num_pos_args, emit->scope->scope_flags, 0); } } @@ -473,24 +646,36 @@ STATIC bool emit_native_last_emit_was_return_value(emit_t *emit) { return emit->last_emit_was_return_value; } +STATIC void ensure_extra_stack(emit_t *emit, size_t delta) { + if (emit->stack_size + delta > emit->stack_info_alloc) { + size_t new_alloc = (emit->stack_size + delta + 8) & ~3; + emit->stack_info = m_renew(stack_info_t, emit->stack_info, emit->stack_info_alloc, new_alloc); + emit->stack_info_alloc = new_alloc; + } +} + STATIC void adjust_stack(emit_t *emit, mp_int_t stack_size_delta) { assert((mp_int_t)emit->stack_size + stack_size_delta >= 0); + assert((mp_int_t)emit->stack_size + stack_size_delta <= (mp_int_t)emit->stack_info_alloc); emit->stack_size += 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) { DEBUG_printf("adjust_stack_size(" INT_FMT ")\n", delta); + if (delta > 0) { + ensure_extra_stack(emit, delta); + } // If we are adjusting the stack in a positive direction (pushing) then we // need to fill in values for the stack kind and vtype of the newly-pushed // entries. These should be set to "value" (ie not reg or imm) because we @@ -527,7 +712,12 @@ STATIC stack_info_t *peek_stack(emit_t *emit, mp_uint_t depth) { // depth==0 is top, depth==1 is before top, etc STATIC vtype_kind_t peek_vtype(emit_t *emit, mp_uint_t depth) { - return peek_stack(emit, depth)->vtype; + if (emit->do_viper_types) { + return peek_stack(emit, depth)->vtype; + } else { + // Type is always PYOBJ even if the intermediate stored value is not + return VTYPE_PYOBJ; + } } // pos=1 is TOS, pos=2 is next, etc @@ -539,7 +729,7 @@ STATIC void need_reg_single(emit_t *emit, int reg_needed, int skip_stack_pos) { stack_info_t *si = &emit->stack_info[i]; if (si->kind == STACK_REG && si->data.u_reg == reg_needed) { si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } } @@ -550,8 +740,28 @@ STATIC void need_reg_all(emit_t *emit) { stack_info_t *si = &emit->stack_info[i]; if (si->kind == STACK_REG) { si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); + } + } +} + +STATIC vtype_kind_t load_reg_stack_imm(emit_t *emit, int reg_dest, const stack_info_t *si, bool convert_to_pyobj) { + if (!convert_to_pyobj && emit->do_viper_types) { + ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + return si->vtype; + } else { + if (si->vtype == VTYPE_PYOBJ) { + ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + } else if (si->vtype == VTYPE_BOOL) { + emit_native_mov_reg_const(emit, reg_dest, MP_F_CONST_FALSE_OBJ + si->data.u_imm); + } else if (si->vtype == VTYPE_INT || si->vtype == VTYPE_UINT) { + ASM_MOV_REG_IMM(emit->as, reg_dest, (uintptr_t)MP_OBJ_NEW_SMALL_INT(si->data.u_imm)); + } else if (si->vtype == VTYPE_PTR_NONE) { + emit_native_mov_reg_const(emit, reg_dest, MP_F_CONST_NONE_OBJ); + } else { + mp_raise_NotImplementedError(translate("conversion to object")); } + return VTYPE_PYOBJ; } } @@ -562,7 +772,7 @@ STATIC void need_stack_settled(emit_t *emit) { if (si->kind == STACK_REG) { DEBUG_printf(" reg(%u) to local(%u)\n", si->data.u_reg, emit->stack_start + i); si->kind = STACK_VALUE; - ASM_MOV_LOCAL_REG(emit->as, emit->stack_start + i, si->data.u_reg); + emit_native_mov_state_reg(emit, emit->stack_start + i, si->data.u_reg); } } for (int i = 0; i < emit->stack_size; i++) { @@ -570,7 +780,8 @@ STATIC void need_stack_settled(emit_t *emit) { if (si->kind == STACK_IMM) { DEBUG_printf(" imm(" INT_FMT ") to local(%u)\n", si->data.u_imm, emit->stack_start + i); si->kind = STACK_VALUE; - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + i, si->data.u_imm, REG_TEMP0); + si->vtype = load_reg_stack_imm(emit, REG_TEMP0, si, false); + emit_native_mov_state_reg(emit, emit->stack_start + i, REG_TEMP0); } } } @@ -582,7 +793,7 @@ STATIC void emit_access_stack(emit_t *emit, int pos, vtype_kind_t *vtype, int re *vtype = si->vtype; switch (si->kind) { case STACK_VALUE: - ASM_MOV_REG_LOCAL(emit->as, reg_dest, emit->stack_start + emit->stack_size - pos); + emit_native_mov_reg_state(emit, reg_dest, emit->stack_start + emit->stack_size - pos); break; case STACK_REG: @@ -592,7 +803,7 @@ STATIC void emit_access_stack(emit_t *emit, int pos, vtype_kind_t *vtype, int re break; case STACK_IMM: - ASM_MOV_REG_IMM(emit->as, reg_dest, si->data.u_imm); + *vtype = load_reg_stack_imm(emit, reg_dest, si, false); break; } } @@ -604,7 +815,7 @@ STATIC void emit_fold_stack_top(emit_t *emit, int reg_dest) { si[0] = si[1]; if (si->kind == STACK_VALUE) { // if folded element was on the stack we need to put it in a register - ASM_MOV_REG_LOCAL(emit->as, reg_dest, emit->stack_start + emit->stack_size - 1); + emit_native_mov_reg_state(emit, reg_dest, emit->stack_start + emit->stack_size - 1); si->kind = STACK_REG; si->data.u_reg = reg_dest; } @@ -658,6 +869,7 @@ STATIC void emit_post_top_set_vtype(emit_t *emit, vtype_kind_t new_vtype) { } STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg) { + ensure_extra_stack(emit, 1); stack_info_t *si = &emit->stack_info[emit->stack_size]; si->vtype = vtype; si->kind = STACK_REG; @@ -666,6 +878,7 @@ STATIC void emit_post_push_reg(emit_t *emit, vtype_kind_t vtype, int reg) { } STATIC void emit_post_push_imm(emit_t *emit, vtype_kind_t vtype, mp_int_t imm) { + ensure_extra_stack(emit, 1); stack_info_t *si = &emit->stack_info[emit->stack_size]; si->vtype = vtype; si->kind = STACK_IMM; @@ -693,36 +906,20 @@ STATIC void emit_post_push_reg_reg_reg_reg(emit_t *emit, vtype_kind_t vtypea, in STATIC void emit_call(emit_t *emit, mp_fun_kind_t fun_kind) { need_reg_all(emit); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } STATIC void emit_call_with_imm_arg(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg) { need_reg_all(emit); ASM_MOV_REG_IMM(emit->as, arg_reg, arg_val); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); -} - -// the first arg is stored in the code aligned on a mp_uint_t boundary -STATIC void emit_call_with_imm_arg_aligned(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val, int arg_reg) { - need_reg_all(emit); - ASM_MOV_REG_ALIGNED_IMM(emit->as, arg_reg, arg_val); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } STATIC void emit_call_with_2_imm_args(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val1, int arg_reg1, mp_int_t arg_val2, int arg_reg2) { need_reg_all(emit); ASM_MOV_REG_IMM(emit->as, arg_reg1, arg_val1); ASM_MOV_REG_IMM(emit->as, arg_reg2, arg_val2); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); -} - -// the first arg is stored in the code aligned on a mp_uint_t boundary -STATIC void emit_call_with_3_imm_args_and_first_aligned(emit_t *emit, mp_fun_kind_t fun_kind, mp_int_t arg_val1, int arg_reg1, mp_int_t arg_val2, int arg_reg2, mp_int_t arg_val3, int arg_reg3) { - need_reg_all(emit); - ASM_MOV_REG_ALIGNED_IMM(emit->as, arg_reg1, arg_val1); - ASM_MOV_REG_IMM(emit->as, arg_reg2, arg_val2); - ASM_MOV_REG_IMM(emit->as, arg_reg3, arg_val3); - ASM_CALL_IND(emit->as, mp_fun_table[fun_kind], fun_kind); + ASM_CALL_IND(emit->as, fun_kind); } // vtype of all n_pop objects is VTYPE_PYOBJ @@ -739,27 +936,8 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de // must convert them to VTYPE_PYOBJ for viper code if (si->kind == STACK_IMM) { si->kind = STACK_VALUE; - switch (si->vtype) { - case VTYPE_PYOBJ: - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, si->data.u_imm, reg_dest); - break; - case VTYPE_BOOL: - if (si->data.u_imm == 0) { - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (mp_uint_t)mp_const_false, reg_dest); - } else { - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (mp_uint_t)mp_const_true, reg_dest); - } - si->vtype = VTYPE_PYOBJ; - break; - case VTYPE_INT: - case VTYPE_UINT: - ASM_MOV_LOCAL_IMM_VIA(emit->as, emit->stack_start + emit->stack_size - 1 - i, (uintptr_t)MP_OBJ_NEW_SMALL_INT(si->data.u_imm), reg_dest); - si->vtype = VTYPE_PYOBJ; - break; - default: - // not handled - mp_raise_NotImplementedError(translate("conversion to object")); - } + si->vtype = load_reg_stack_imm(emit, reg_dest, si, true); + emit_native_mov_state_reg(emit, emit->stack_start + emit->stack_size - 1 - i, reg_dest); } // verify that this value is on the stack @@ -771,9 +949,9 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de stack_info_t *si = &emit->stack_info[emit->stack_size - 1 - i]; if (si->vtype != VTYPE_PYOBJ) { mp_uint_t local_num = emit->stack_start + emit->stack_size - 1 - i; - ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, local_num); + emit_native_mov_reg_state(emit, REG_ARG_1, local_num); emit_call_with_imm_arg(emit, MP_F_CONVERT_NATIVE_TO_OBJ, si->vtype, REG_ARG_2); // arg2 = type - ASM_MOV_LOCAL_REG(emit->as, local_num, REG_RET); + emit_native_mov_state_reg(emit, local_num, REG_RET); si->vtype = VTYPE_PYOBJ; DEBUG_printf(" convert_native_to_obj(local_num=" UINT_FMT ")\n", local_num); } @@ -781,59 +959,266 @@ STATIC void emit_get_stack_pointer_to_reg_for_pop(emit_t *emit, mp_uint_t reg_de // Adujust the stack for a pop of n_pop items, and load the stack pointer into reg_dest. adjust_stack(emit, -n_pop); - ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, emit->stack_start + emit->stack_size); + emit_native_mov_reg_state_addr(emit, reg_dest, emit->stack_start + emit->stack_size); } // vtype of all n_push objects is VTYPE_PYOBJ STATIC void emit_get_stack_pointer_to_reg_for_push(emit_t *emit, mp_uint_t reg_dest, mp_uint_t n_push) { need_reg_all(emit); + ensure_extra_stack(emit, n_push); for (mp_uint_t i = 0; i < n_push; i++) { emit->stack_info[emit->stack_size + i].kind = STACK_VALUE; emit->stack_info[emit->stack_size + i].vtype = VTYPE_PYOBJ; } - ASM_MOV_REG_LOCAL_ADDR(emit->as, reg_dest, emit->stack_start + emit->stack_size); + emit_native_mov_reg_state_addr(emit, reg_dest, emit->stack_start + emit->stack_size); adjust_stack(emit, n_push); } +STATIC void emit_native_push_exc_stack(emit_t *emit, uint label, bool is_finally) { + if (emit->exc_stack_size + 1 > emit->exc_stack_alloc) { + size_t new_alloc = emit->exc_stack_alloc + 4; + emit->exc_stack = m_renew(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc, new_alloc); + emit->exc_stack_alloc = new_alloc; + } + + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size++]; + e->label = label; + e->is_finally = is_finally; + e->unwind_label = UNWIND_LABEL_UNUSED; + e->is_active = true; + + ASM_MOV_REG_PCREL(emit->as, REG_RET, label); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); +} + +STATIC void emit_native_leave_exc_stack(emit_t *emit, bool start_of_handler) { + assert(emit->exc_stack_size > 0); + + // Get current exception handler and deactivate it + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + e->is_active = false; + + // Find next innermost active exception handler, to restore as current handler + for (--e; e >= emit->exc_stack && !e->is_active; --e) { + } + + // Update the PC of the new exception handler + if (e < emit->exc_stack) { + // No active handler, clear handler PC to zero + if (start_of_handler) { + // Optimisation: PC is already cleared by global exc handler + return; + } + ASM_XOR_REG_REG(emit->as, REG_RET, REG_RET); + } else { + // Found new active handler, get its PC + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + } + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); +} + +STATIC exc_stack_entry_t *emit_native_pop_exc_stack(emit_t *emit) { + assert(emit->exc_stack_size > 0); + exc_stack_entry_t *e = &emit->exc_stack[--emit->exc_stack_size]; + assert(e->is_active == false); + return e; +} + +STATIC void emit_load_reg_with_ptr(emit_t *emit, int reg, mp_uint_t ptr, size_t table_off) { + if (!emit->do_viper_types) { + // Skip qstr names of arguments + table_off += emit->scope->num_pos_args + emit->scope->num_kwonly_args; + } + if (emit->pass == MP_PASS_EMIT) { + emit->const_table[table_off] = ptr; + } + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_TEMP0, offsetof(mp_obj_fun_bc_t, const_table) / sizeof(uintptr_t)); + ASM_LOAD_REG_REG_OFFSET(emit->as, reg, REG_TEMP0, table_off); +} + +STATIC void emit_load_reg_with_object(emit_t *emit, int reg, mp_obj_t obj) { + size_t table_off = emit->const_table_cur_obj++; + emit_load_reg_with_ptr(emit, reg, (mp_uint_t)obj, table_off); +} + +STATIC void emit_load_reg_with_raw_code(emit_t *emit, int reg, mp_raw_code_t *rc) { + size_t table_off = emit->const_table_num_obj + emit->const_table_cur_raw_code++; + emit_load_reg_with_ptr(emit, reg, (mp_uint_t)rc, table_off); +} + STATIC void emit_native_label_assign(emit_t *emit, mp_uint_t l) { DEBUG_printf("label_assign(" UINT_FMT ")\n", l); + + bool is_finally = false; + if (emit->exc_stack_size > 0) { + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + is_finally = e->is_finally && e->label == l; + } + + if (is_finally) { + // Label is at start of finally handler: store TOS into exception slot + vtype_kind_t vtype; + emit_pre_pop_reg(emit, &vtype, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); + } + emit_native_pre(emit); // need to commit stack because we can jump here from elsewhere need_stack_settled(emit); mp_asm_base_label_assign(&emit->as->base, l); emit_post(emit); + + if (is_finally) { + // Label is at start of finally handler: pop exception stack + emit_native_leave_exc_stack(emit, false); + } } -STATIC void emit_native_import_name(emit_t *emit, qstr qst) { - DEBUG_printf("import_name %s\n", qstr_str(qst)); +STATIC void emit_native_global_exc_entry(emit_t *emit) { + // Note: 4 labels are reserved for this function, starting at *emit->label_slot - // get arguments from stack: arg2 = fromlist, arg3 = level - // if using viper types these arguments must be converted to proper objects - if (emit->do_viper_types) { - // fromlist should be None or a tuple - stack_info_t *top = peek_stack(emit, 0); - if (top->vtype == VTYPE_PTR_NONE) { - emit_pre_pop_discard(emit); - ASM_MOV_REG_IMM(emit->as, REG_ARG_2, (mp_uint_t)mp_const_none); + emit->exit_label = *emit->label_slot; + + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + mp_uint_t nlr_label = *emit->label_slot + 1; + mp_uint_t start_label = *emit->label_slot + 2; + mp_uint_t global_except_label = *emit->label_slot + 3; + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Set new globals + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_FUN_OBJ(emit)); + ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_1, REG_ARG_1, offsetof(mp_obj_fun_bc_t, globals) / sizeof(uintptr_t)); + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + + // Save old globals (or NULL if globals didn't change) + emit_native_mov_state_reg(emit, LOCAL_IDX_OLD_GLOBALS(emit), REG_RET); + } + + if (emit->scope->exc_stack_size == 0) { + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Optimisation: if globals didn't change don't push the nlr context + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, start_label, false); + } + + // Wrap everything in an nlr context + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + emit_call(emit, MP_F_NLR_PUSH); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, start_label, true); + } else { + // Clear the unwind state + ASM_XOR_REG_REG(emit->as, REG_TEMP0, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_TEMP0); + + // Put PC of start code block into REG_LOCAL_1 + ASM_MOV_REG_PCREL(emit->as, REG_LOCAL_1, start_label); + + // Wrap everything in an nlr context + emit_native_label_assign(emit, nlr_label); + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_2, LOCAL_IDX_EXC_HANDLER_UNWIND(emit)); + ASM_MOV_REG_LOCAL_ADDR(emit->as, REG_ARG_1, 0); + emit_call(emit, MP_F_NLR_PUSH); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_LOCAL_2); + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, global_except_label, true); + + // Clear PC of current code block, and jump there to resume execution + ASM_XOR_REG_REG(emit->as, REG_TEMP0, REG_TEMP0); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_TEMP0); + ASM_JUMP_REG(emit->as, REG_LOCAL_1); + + // Global exception handler: check for valid exception handler + emit_native_label_assign(emit, global_except_label); + ASM_MOV_REG_LOCAL(emit->as, REG_LOCAL_1, LOCAL_IDX_EXC_HANDLER_PC(emit)); + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_LOCAL_1, nlr_label, false); + } + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + // Restore old globals + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_OLD_GLOBALS(emit)); + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + } + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + // Store return value in state[0] + ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, LOCAL_IDX_EXC_VAL(emit)); + ASM_STORE_REG_REG_OFFSET(emit->as, REG_TEMP0, REG_GENERATOR_STATE, offsetof(mp_code_state_t, state) / sizeof(uintptr_t)); + + // Load return kind + ASM_MOV_REG_IMM(emit->as, REG_RET, MP_VM_RETURN_EXCEPTION); + + ASM_EXIT(emit->as); } else { - vtype_kind_t vtype_fromlist; - emit_pre_pop_reg(emit, &vtype_fromlist, REG_ARG_2); - assert(vtype_fromlist == VTYPE_PYOBJ); + // Re-raise exception out to caller + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); } - // level argument should be an immediate integer - top = peek_stack(emit, 0); - assert(top->vtype == VTYPE_INT && top->kind == STACK_IMM); - ASM_MOV_REG_IMM(emit->as, REG_ARG_3, (mp_uint_t)MP_OBJ_NEW_SMALL_INT(top->data.u_imm)); - emit_pre_pop_discard(emit); + // Label for start of function + emit_native_label_assign(emit, start_label); - } else { - vtype_kind_t vtype_fromlist; - vtype_kind_t vtype_level; - emit_pre_pop_reg_reg(emit, &vtype_fromlist, REG_ARG_2, &vtype_level, REG_ARG_3); - assert(vtype_fromlist == VTYPE_PYOBJ); - assert(vtype_level == VTYPE_PYOBJ); + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_GEN_PC(emit)); + ASM_JUMP_REG(emit->as, REG_TEMP0); + emit->start_offset = mp_asm_base_get_code_pos(&emit->as->base); + + // This is the first entry of the generator + + // Check LOCAL_IDX_EXC_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } } +} + +STATIC void emit_native_global_exc_exit(emit_t *emit) { + // Label for end of function + emit_native_label_assign(emit, emit->exit_label); + + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Get old globals + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + emit_native_mov_reg_state(emit, REG_ARG_1, LOCAL_IDX_OLD_GLOBALS(emit)); + + if (emit->scope->exc_stack_size == 0) { + // Optimisation: if globals didn't change then don't restore them and don't do nlr_pop + ASM_JUMP_IF_REG_ZERO(emit->as, REG_ARG_1, emit->exit_label + 1, false); + } + + // Restore old globals + emit_call(emit, MP_F_NATIVE_SWAP_GLOBALS); + } + + // Pop the nlr context + emit_call(emit, MP_F_NLR_POP); + + if (!(emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR)) { + if (emit->scope->exc_stack_size == 0) { + // Destination label for above optimisation + emit_native_label_assign(emit, emit->exit_label + 1); + } + } + + // Load return value + ASM_MOV_REG_LOCAL(emit->as, REG_RET, LOCAL_IDX_RET_VAL(emit)); + } + + ASM_EXIT(emit->as); +} + +STATIC void emit_native_import_name(emit_t *emit, qstr qst) { + DEBUG_printf("import_name %s\n", qstr_str(qst)); + + // get arguments from stack: arg2 = fromlist, arg3 = level + // If using viper types these arguments must be converted to proper objects, and + // to accomplish this viper types are turned off for the emit_pre_pop_reg_reg call. + bool orig_do_viper_types = emit->do_viper_types; + emit->do_viper_types = false; + vtype_kind_t vtype_fromlist; + vtype_kind_t vtype_level; + emit_pre_pop_reg_reg(emit, &vtype_fromlist, REG_ARG_2, &vtype_level, REG_ARG_3); + assert(vtype_fromlist == VTYPE_PYOBJ); + assert(vtype_level == VTYPE_PYOBJ); + emit->do_viper_types = orig_do_viper_types; emit_call_with_imm_arg(emit, MP_F_IMPORT_NAME, qst, REG_ARG_1); // arg1 = import name emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); @@ -870,40 +1255,22 @@ STATIC void emit_native_import(emit_t *emit, qstr qst, int kind) { STATIC void emit_native_load_const_tok(emit_t *emit, mp_token_kind_t tok) { DEBUG_printf("load_const_tok(tok=%u)\n", tok); - emit_native_pre(emit); - vtype_kind_t vtype; - 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; - default: - assert(tok == MP_TOKEN_ELLIPSIS); - vtype = VTYPE_PYOBJ; val = (mp_uint_t)&mp_const_ellipsis_obj; break; - } + if (tok == MP_TOKEN_ELLIPSIS) { + emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj)); } 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; - default: - assert(tok == MP_TOKEN_ELLIPSIS); - val = (mp_uint_t)&mp_const_ellipsis_obj; break; + emit_native_pre(emit); + if (tok == MP_TOKEN_KW_NONE) { + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + } else { + emit_post_push_imm(emit, VTYPE_BOOL, tok == MP_TOKEN_KW_FALSE ? 0 : 1); } } - emit_post_push_imm(emit, vtype, val); } STATIC void emit_native_load_const_small_int(emit_t *emit, mp_int_t arg) { DEBUG_printf("load_const_small_int(int=" INT_FMT ")\n", arg); emit_native_pre(emit); - if (emit->do_viper_types) { - emit_post_push_imm(emit, VTYPE_INT, arg); - } else { - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)MP_OBJ_NEW_SMALL_INT(arg)); - } + emit_post_push_imm(emit, VTYPE_INT, arg); } STATIC void emit_native_load_const_str(emit_t *emit, qstr qst) { @@ -924,7 +1291,7 @@ STATIC void emit_native_load_const_str(emit_t *emit, qstr qst) { STATIC void emit_native_load_const_obj(emit_t *emit, mp_obj_t obj) { emit_native_pre(emit); need_reg_single(emit, REG_RET, 0); - ASM_MOV_REG_ALIGNED_IMM(emit->as, REG_RET, (mp_uint_t)obj); + emit_load_reg_with_object(emit, REG_RET, obj); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -940,19 +1307,11 @@ STATIC void emit_native_load_fast(emit_t *emit, qstr qst, mp_uint_t local_num) { EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("local '%q' used before type known"), qst); } emit_native_pre(emit); - if (local_num == 0) { - emit_post_push_reg(emit, vtype, REG_LOCAL_1); - } else if (local_num == 1) { - emit_post_push_reg(emit, vtype, REG_LOCAL_2); - } else if (local_num == 2) { - emit_post_push_reg(emit, vtype, REG_LOCAL_3); + if (local_num < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit)) { + emit_post_push_reg(emit, vtype, reg_local_table[local_num]); } else { need_reg_single(emit, REG_TEMP0, 0); - if (emit->do_viper_types) { - ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, local_num - REG_LOCAL_NUM); - } else { - ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, STATE_START + emit->n_state - 1 - local_num); - } + emit_native_mov_reg_state(emit, REG_TEMP0, LOCAL_IDX_LOCAL_VAR(emit, local_num)); emit_post_push_reg(emit, vtype, REG_TEMP0); } } @@ -987,23 +1346,9 @@ STATIC void emit_native_load_global(emit_t *emit, qstr qst, int kind) { DEBUG_printf("load_global(%s)\n", qstr_str(qst)); if (emit->do_viper_types) { // check for builtin casting operators - if (qst == MP_QSTR_int) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_INT); - return; - } else if (qst == MP_QSTR_uint) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_UINT); - return; - } else if (qst == MP_QSTR_ptr) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR); - return; - } else if (qst == MP_QSTR_ptr8) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR8); - return; - } else if (qst == MP_QSTR_ptr16) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR16); - return; - } else if (qst == MP_QSTR_ptr32) { - emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, VTYPE_PTR32); + int native_type = mp_native_type_from_qstr(qst); + if (native_type >= MP_NATIVE_TYPE_INT) { + emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, native_type); return; } } @@ -1181,19 +1526,11 @@ STATIC void emit_native_load_subscr(emit_t *emit) { STATIC void emit_native_store_fast(emit_t *emit, qstr qst, mp_uint_t local_num) { vtype_kind_t vtype; - if (local_num == 0) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_1); - } else if (local_num == 1) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_2); - } else if (local_num == 2) { - emit_pre_pop_reg(emit, &vtype, REG_LOCAL_3); + if (local_num < REG_LOCAL_NUM && CAN_USE_REGS_FOR_LOCALS(emit)) { + emit_pre_pop_reg(emit, &vtype, reg_local_table[local_num]); } else { emit_pre_pop_reg(emit, &vtype, REG_TEMP0); - if (emit->do_viper_types) { - ASM_MOV_LOCAL_REG(emit->as, local_num - REG_LOCAL_NUM, REG_TEMP0); - } else { - ASM_MOV_LOCAL_REG(emit->as, STATE_START + emit->n_state - 1 - local_num, REG_TEMP0); - } + emit_native_mov_state_reg(emit, LOCAL_IDX_LOCAL_VAR(emit, local_num), REG_TEMP0); } emit_post(emit); @@ -1341,10 +1678,6 @@ STATIC void emit_native_store_subscr(emit_t *emit) { } #endif ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 1); - #if N_ARM - asm_arm_strh_reg_reg_reg(emit->as, reg_value, reg_base, reg_index); - return; - #endif ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 2*index to base reg_base = reg_index; } @@ -1361,11 +1694,12 @@ STATIC void emit_native_store_subscr(emit_t *emit) { break; } #endif - ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 2); #if N_ARM + ASM_MOV_REG_IMM(emit->as, reg_index, index_value); asm_arm_str_reg_reg_reg(emit->as, reg_value, reg_base, reg_index); return; #endif + ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 2); ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 4*index to base reg_base = reg_index; } @@ -1541,7 +1875,7 @@ STATIC void emit_native_jump(emit_t *emit, mp_uint_t label) { emit_post(emit); } -STATIC void emit_native_jump_helper(emit_t *emit, bool pop) { +STATIC void emit_native_jump_helper(emit_t *emit, bool cond, mp_uint_t label, bool pop) { vtype_kind_t vtype = peek_vtype(emit, 0); if (vtype == VTYPE_PYOBJ) { emit_pre_pop_reg(emit, &vtype, REG_ARG_1); @@ -1566,34 +1900,69 @@ STATIC void emit_native_jump_helper(emit_t *emit, bool pop) { } // need to commit stack because we may jump elsewhere need_stack_settled(emit); -} - -STATIC void emit_native_pop_jump_if(emit_t *emit, bool cond, mp_uint_t label) { - DEBUG_printf("pop_jump_if(cond=%u, label=" UINT_FMT ")\n", cond, label); - emit_native_jump_helper(emit, true); + // Emit the jump if (cond) { - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label, vtype == VTYPE_PYOBJ); } else { - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label, vtype == VTYPE_PYOBJ); + } + if (!pop) { + adjust_stack(emit, -1); } emit_post(emit); } +STATIC void emit_native_pop_jump_if(emit_t *emit, bool cond, mp_uint_t label) { + DEBUG_printf("pop_jump_if(cond=%u, label=" UINT_FMT ")\n", cond, label); + emit_native_jump_helper(emit, cond, label, true); +} + STATIC void emit_native_jump_if_or_pop(emit_t *emit, bool cond, mp_uint_t label) { DEBUG_printf("jump_if_or_pop(cond=%u, label=" UINT_FMT ")\n", cond, label); - emit_native_jump_helper(emit, false); - if (cond) { - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); - } else { - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label); - } - adjust_stack(emit, -1); - emit_post(emit); + emit_native_jump_helper(emit, cond, label, false); } STATIC void emit_native_unwind_jump(emit_t *emit, mp_uint_t label, mp_uint_t except_depth) { - (void)except_depth; - emit_native_jump(emit, label & ~MP_EMIT_BREAK_FROM_FOR); // TODO properly + if (except_depth > 0) { + exc_stack_entry_t *first_finally = NULL; + exc_stack_entry_t *prev_finally = NULL; + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + for (; except_depth > 0; --except_depth, --e) { + if (e->is_finally && e->is_active) { + // Found an active finally handler + if (first_finally == NULL) { + first_finally = e; + } + if (prev_finally != NULL) { + // Mark prev finally as needed to unwind a jump + prev_finally->unwind_label = e->label; + } + prev_finally = e; + } + } + if (prev_finally == NULL) { + // No finally, handle the jump ourselves + // First, restore the exception handler address for the jump + if (e < emit->exc_stack) { + ASM_XOR_REG_REG(emit->as, REG_RET, REG_RET); + } else { + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + } + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); + } else { + // Last finally should do our jump for us + // Mark finally as needing to decide the type of jump + prev_finally->unwind_label = UNWIND_LABEL_DO_FINAL_UNWIND; + ASM_MOV_REG_PCREL(emit->as, REG_RET, label & ~MP_EMIT_BREAK_FROM_FOR); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_RET); + // Cancel any active exception (see also emit_native_pop_except) + emit_native_mov_reg_const(emit, REG_RET, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_RET); + // Jump to the innermost active finally + label = first_finally->label; + } + } + emit_native_jump(emit, label & ~MP_EMIT_BREAK_FROM_FOR); } STATIC void emit_native_setup_with(emit_t *emit, mp_uint_t label) { @@ -1629,13 +1998,10 @@ STATIC void emit_native_setup_with(emit_t *emit, mp_uint_t label) { // need to commit stack because we may jump elsewhere need_stack_settled(emit); - emit_get_stack_pointer_to_reg_for_push(emit, REG_ARG_1, sizeof(nlr_buf_t) / sizeof(mp_uint_t)); // arg1 = pointer to nlr buf - emit_call(emit, MP_F_NLR_PUSH); - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); + emit_native_push_exc_stack(emit, label, true); - emit_access_stack(emit, sizeof(nlr_buf_t) / sizeof(mp_uint_t) + 1, &vtype, REG_RET); // access return value of __enter__ - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); // push return value of __enter__ - // stack: (..., __exit__, self, as_value, nlr_buf, as_value) + emit_native_dup_top(emit); + // stack: (..., __exit__, self, as_value, as_value) } STATIC void emit_native_setup_block(emit_t *emit, mp_uint_t label, int kind) { @@ -1644,82 +2010,78 @@ STATIC void emit_native_setup_block(emit_t *emit, mp_uint_t label, int kind) { } else { // Set up except and finally emit_native_pre(emit); - // need to commit stack because we may jump elsewhere need_stack_settled(emit); - emit_get_stack_pointer_to_reg_for_push(emit, REG_ARG_1, sizeof(nlr_buf_t) / sizeof(mp_uint_t)); // arg1 = pointer to nlr buf - emit_call(emit, MP_F_NLR_PUSH); - ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, label); + emit_native_push_exc_stack(emit, label, kind == MP_EMIT_SETUP_BLOCK_FINALLY); emit_post(emit); } } STATIC void emit_native_with_cleanup(emit_t *emit, mp_uint_t label) { - // note: label+1 is available as an auxiliary label + // Note: 3 labels are reserved for this function, starting at *emit->label_slot - // stack: (..., __exit__, self, as_value, nlr_buf) + // stack: (..., __exit__, self, as_value) emit_native_pre(emit); - emit_call(emit, MP_F_NLR_POP); - adjust_stack(emit, -(mp_int_t)(sizeof(nlr_buf_t) / sizeof(mp_uint_t)) - 1); + emit_native_leave_exc_stack(emit, false); + adjust_stack(emit, -1); // stack: (..., __exit__, self) + // Label for case where __exit__ is called from an unwind jump + emit_native_label_assign(emit, *emit->label_slot + 2); + // call __exit__ - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 5); emit_call_with_2_imm_args(emit, MP_F_CALL_METHOD_N_KW, 3, REG_ARG_1, 0, REG_ARG_2); - // jump to after with cleanup nlr_catch block - adjust_stack(emit, 1); // dummy nlr_buf.prev - emit_native_load_const_tok(emit, MP_TOKEN_KW_NONE); // nlr_buf.ret_val = no exception - emit_native_jump(emit, label + 1); + // Replace exc with None and finish + emit_native_jump(emit, *emit->label_slot); // nlr_catch - emit_native_label_assign(emit, label); + // Don't use emit_native_label_assign because this isn't a real finally label + mp_asm_base_label_assign(&emit->as->base, label); - // adjust stack counter for: __exit__, self, as_value - adjust_stack(emit, 3); - // stack: (..., __exit__, self, as_value, nlr_buf.prev, nlr_buf.ret_val) + // Leave with's exception handler + emit_native_leave_exc_stack(emit, true); - vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_ARG_1); // get the thrown value (exc) - adjust_stack(emit, -2); // discard nlr_buf.prev and as_value + // Adjust stack counter for: __exit__, self (implicitly discard as_value which is above self) + emit_native_adjust_stack_size(emit, 2); // stack: (..., __exit__, self) - // REG_ARG_1=exc - emit_pre_pop_reg(emit, &vtype, REG_ARG_2); // self - emit_pre_pop_reg(emit, &vtype, REG_ARG_3); // __exit__ - adjust_stack(emit, 1); // dummy nlr_buf.prev - emit_post_push_reg(emit, vtype, REG_ARG_1); // push exc to save it for later - emit_post_push_reg(emit, vtype, REG_ARG_3); // __exit__ - emit_post_push_reg(emit, vtype, REG_ARG_2); // self - // stack: (..., exc, __exit__, self) - // REG_ARG_1=exc + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); // get exc + + // Check if exc is None and jump to non-exc handler if it is + emit_native_mov_reg_const(emit, REG_ARG_2, MP_F_CONST_NONE_OBJ); + ASM_JUMP_IF_REG_EQ(emit->as, REG_ARG_1, REG_ARG_2, *emit->label_slot + 2); ASM_LOAD_REG_REG_OFFSET(emit->as, REG_ARG_2, REG_ARG_1, 0); // get type(exc) emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_2); // push type(exc) emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_1); // push exc value - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); // traceback info - // stack: (..., exc, __exit__, self, type(exc), exc, traceback) + emit_post_push_imm(emit, VTYPE_PTR_NONE, 0); // traceback info + // Stack: (..., __exit__, self, type(exc), exc, traceback) // call __exit__ method emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 5); emit_call_with_2_imm_args(emit, MP_F_CALL_METHOD_N_KW, 3, REG_ARG_1, 0, REG_ARG_2); - // stack: (..., exc) + // Stack: (...) - // if REG_RET is true then we need to replace top-of-stack with None (swallow exception) + // If REG_RET is true then we need to replace exception with None (swallow exception) if (REG_ARG_1 != REG_RET) { ASM_MOV_REG_REG(emit->as, REG_ARG_1, REG_RET); } emit_call(emit, MP_F_OBJ_IS_TRUE); - ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label + 1); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, *emit->label_slot + 1, true); - // replace exc with None - emit_pre_pop_discard(emit); - emit_post_push_imm(emit, VTYPE_PYOBJ, (mp_uint_t)mp_const_none); + // Replace exception with None + emit_native_label_assign(emit, *emit->label_slot); + emit_native_mov_reg_const(emit, REG_TEMP0, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); // end of with cleanup nlr_catch block - emit_native_label_assign(emit, label + 1); + emit_native_label_assign(emit, *emit->label_slot + 1); + + // Exception is in nlr_buf.ret_val slot } STATIC void emit_native_end_finally(emit_t *emit) { @@ -1728,10 +2090,23 @@ STATIC void emit_native_end_finally(emit_t *emit) { // if exc == None: pass // else: raise exc // the check if exc is None is done in the MP_F_NATIVE_RAISE stub - vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_ARG_1); // get nlr_buf.ret_val - emit_pre_pop_discard(emit); // discard nlr_buf.prev + emit_native_pre(emit); + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); emit_call(emit, MP_F_NATIVE_RAISE); + + // Get state for this finally and see if we need to unwind + exc_stack_entry_t *e = emit_native_pop_exc_stack(emit); + if (e->unwind_label != UNWIND_LABEL_UNUSED) { + ASM_MOV_REG_LOCAL(emit->as, REG_RET, LOCAL_IDX_EXC_HANDLER_UNWIND(emit)); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, *emit->label_slot, false); + if (e->unwind_label == UNWIND_LABEL_DO_FINAL_UNWIND) { + ASM_JUMP_REG(emit->as, REG_RET); + } else { + emit_native_jump(emit, e->unwind_label); + } + emit_native_label_assign(emit, *emit->label_slot); + } + emit_post(emit); } @@ -1758,8 +2133,13 @@ STATIC void emit_native_for_iter(emit_t *emit, mp_uint_t label) { emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_1, MP_OBJ_ITER_BUF_NSLOTS); adjust_stack(emit, MP_OBJ_ITER_BUF_NSLOTS); emit_call(emit, MP_F_NATIVE_ITERNEXT); + #ifdef NDEBUG + MP_STATIC_ASSERT(MP_OBJ_STOP_ITERATION == 0); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_RET, label, false); + #else ASM_MOV_REG_IMM(emit->as, REG_TEMP1, (mp_uint_t)MP_OBJ_STOP_ITERATION); ASM_JUMP_IF_REG_EQ(emit->as, REG_RET, REG_TEMP1, label); + #endif emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -1772,13 +2152,16 @@ STATIC void emit_native_for_iter_end(emit_t *emit) { STATIC void emit_native_pop_block(emit_t *emit) { emit_native_pre(emit); - emit_call(emit, MP_F_NLR_POP); - adjust_stack(emit, -(mp_int_t)(sizeof(nlr_buf_t) / sizeof(mp_uint_t)) + 1); + if (!emit->exc_stack[emit->exc_stack_size - 1].is_finally) { + emit_native_leave_exc_stack(emit, false); + } emit_post(emit); } STATIC void emit_native_pop_except(emit_t *emit) { - (void)emit; + // Cancel any active exception so subsequent handlers don't see it + emit_native_mov_reg_const(emit, REG_TEMP0, MP_F_CONST_NONE_OBJ); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); } STATIC void emit_native_unary_op(emit_t *emit, mp_unary_op_t op) { @@ -1939,7 +2322,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 { @@ -2015,8 +2398,7 @@ STATIC void emit_native_build_slice(emit_t *emit, mp_uint_t n_args) { emit_pre_pop_reg_reg(emit, &vtype_stop, REG_ARG_2, &vtype_start, REG_ARG_1); // arg1 = start, arg2 = stop assert(vtype_start == VTYPE_PYOBJ); assert(vtype_stop == VTYPE_PYOBJ); - emit_call_with_imm_arg(emit, MP_F_NEW_SLICE, (mp_uint_t)mp_const_none, REG_ARG_3); // arg3 = step - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); + emit_native_mov_reg_const(emit, REG_ARG_3, MP_F_CONST_NONE_OBJ); // arg3 = step } else { assert(n_args == 3); vtype_kind_t vtype_start, vtype_stop, vtype_step; @@ -2024,9 +2406,9 @@ STATIC void emit_native_build_slice(emit_t *emit, mp_uint_t n_args) { assert(vtype_start == VTYPE_PYOBJ); assert(vtype_stop == VTYPE_PYOBJ); assert(vtype_step == VTYPE_PYOBJ); - emit_call(emit, MP_F_NEW_SLICE); - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } + emit_call(emit, MP_F_NEW_SLICE); + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } #endif @@ -2081,14 +2463,18 @@ STATIC void emit_native_make_function(emit_t *emit, scope_t *scope, mp_uint_t n_ // call runtime, with type info for args, or don't support dict/default params, or only support Python objects for them emit_native_pre(emit); if (n_pos_defaults == 0 && n_kw_defaults == 0) { - emit_call_with_3_imm_args_and_first_aligned(emit, MP_F_MAKE_FUNCTION_FROM_RAW_CODE, (mp_uint_t)scope->raw_code, REG_ARG_1, (mp_uint_t)MP_OBJ_NULL, REG_ARG_2, (mp_uint_t)MP_OBJ_NULL, REG_ARG_3); + need_reg_all(emit); + ASM_MOV_REG_IMM(emit->as, REG_ARG_2, (mp_uint_t)MP_OBJ_NULL); + ASM_MOV_REG_IMM(emit->as, REG_ARG_3, (mp_uint_t)MP_OBJ_NULL); } else { vtype_kind_t vtype_def_tuple, vtype_def_dict; emit_pre_pop_reg_reg(emit, &vtype_def_dict, REG_ARG_3, &vtype_def_tuple, REG_ARG_2); assert(vtype_def_tuple == VTYPE_PYOBJ); assert(vtype_def_dict == VTYPE_PYOBJ); - emit_call_with_imm_arg_aligned(emit, MP_F_MAKE_FUNCTION_FROM_RAW_CODE, (mp_uint_t)scope->raw_code, REG_ARG_1); + need_reg_all(emit); } + emit_load_reg_with_raw_code(emit, REG_ARG_1, scope->raw_code); + ASM_CALL_IND(emit->as, MP_F_MAKE_FUNCTION_FROM_RAW_CODE); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -2101,8 +2487,8 @@ STATIC void emit_native_make_closure(emit_t *emit, scope_t *scope, mp_uint_t n_c emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, n_closed_over + 2); ASM_MOV_REG_IMM(emit->as, REG_ARG_2, 0x100 | n_closed_over); } - ASM_MOV_REG_ALIGNED_IMM(emit->as, REG_ARG_1, (mp_uint_t)scope->raw_code); - ASM_CALL_IND(emit->as, mp_fun_table[MP_F_MAKE_CLOSURE_FROM_RAW_CODE], MP_F_MAKE_CLOSURE_FROM_RAW_CODE); + emit_load_reg_with_raw_code(emit, REG_ARG_1, scope->raw_code); + ASM_CALL_IND(emit->as, MP_F_MAKE_CLOSURE_FROM_RAW_CODE); emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); } @@ -2176,30 +2562,54 @@ STATIC void emit_native_call_method(emit_t *emit, mp_uint_t n_positional, mp_uin STATIC void emit_native_return_value(emit_t *emit) { DEBUG_printf("return_value\n"); + + if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { + // Save pointer to current stack position for caller to access return value + emit_get_stack_pointer_to_reg_for_pop(emit, REG_TEMP0, 1); + emit_native_mov_state_reg(emit, offsetof(mp_code_state_t, sp) / sizeof(uintptr_t), REG_TEMP0); + + // Put return type in return value slot + ASM_MOV_REG_IMM(emit->as, REG_TEMP0, MP_VM_RETURN_NORMAL); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_TEMP0); + + // Do the unwinding jump to get to the return handler + emit_native_unwind_jump(emit, emit->exit_label, emit->exc_stack_size); + emit->last_emit_was_return_value = true; + return; + } + if (emit->do_viper_types) { + vtype_kind_t return_vtype = emit->scope->scope_flags >> MP_SCOPE_FLAG_VIPERRET_POS; if (peek_vtype(emit, 0) == VTYPE_PTR_NONE) { emit_pre_pop_discard(emit); - if (emit->return_vtype == VTYPE_PYOBJ) { - ASM_MOV_REG_IMM(emit->as, REG_RET, (mp_uint_t)mp_const_none); + if (return_vtype == VTYPE_PYOBJ) { + emit_native_mov_reg_const(emit, REG_RET, MP_F_CONST_NONE_OBJ); } else { - ASM_MOV_REG_IMM(emit->as, REG_RET, 0); + ASM_MOV_REG_IMM(emit->as, REG_ARG_1, 0); } } else { vtype_kind_t vtype; - emit_pre_pop_reg(emit, &vtype, REG_RET); - if (vtype != emit->return_vtype) { + emit_pre_pop_reg(emit, &vtype, return_vtype == VTYPE_PYOBJ ? REG_RET : REG_ARG_1); + if (vtype != return_vtype) { EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("return expected '%q' but got '%q'"), - vtype_to_qstr(emit->return_vtype), vtype_to_qstr(vtype)); + vtype_to_qstr(return_vtype), vtype_to_qstr(vtype)); } } + if (return_vtype != VTYPE_PYOBJ) { + emit_call_with_imm_arg(emit, MP_F_CONVERT_NATIVE_TO_OBJ, return_vtype, REG_ARG_2); + } } else { vtype_kind_t vtype; emit_pre_pop_reg(emit, &vtype, REG_RET); assert(vtype == VTYPE_PYOBJ); } + if (NEED_GLOBAL_EXC_HANDLER(emit)) { + // Save return value for the global exception handler to use + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_RET); + } + emit_native_unwind_jump(emit, emit->exit_label, emit->exc_stack_size); emit->last_emit_was_return_value = true; - ASM_EXIT(emit->as); } STATIC void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { @@ -2214,29 +2624,101 @@ STATIC void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { } STATIC void emit_native_yield(emit_t *emit, int kind) { - // not supported (for now) - (void)emit; - (void)kind; - mp_raise_NotImplementedError(translate("native yield")); + // Note: 1 (yield) or 3 (yield from) labels are reserved for this function, starting at *emit->label_slot + + if (emit->do_viper_types) { + mp_raise_NotImplementedError(translate("native yield")); + } + emit->scope->scope_flags |= MP_SCOPE_FLAG_GENERATOR; + + need_stack_settled(emit); + + if (kind == MP_EMIT_YIELD_FROM) { + + // Top of yield-from loop, conceptually implementing: + // for item in generator: + // yield item + + // Jump to start of loop + emit_native_jump(emit, *emit->label_slot + 2); + + // Label for top of loop + emit_native_label_assign(emit, *emit->label_slot + 1); + } + + // Save pointer to current stack position for caller to access yielded value + emit_get_stack_pointer_to_reg_for_pop(emit, REG_TEMP0, 1); + emit_native_mov_state_reg(emit, offsetof(mp_code_state_t, sp) / sizeof(uintptr_t), REG_TEMP0); + + // Put return type in return value slot + ASM_MOV_REG_IMM(emit->as, REG_TEMP0, MP_VM_RETURN_YIELD); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_RET_VAL(emit), REG_TEMP0); + + // Save re-entry PC + ASM_MOV_REG_PCREL(emit->as, REG_TEMP0, *emit->label_slot); + emit_native_mov_state_reg(emit, LOCAL_IDX_GEN_PC(emit), REG_TEMP0); + + // Jump to exit handler + ASM_JUMP(emit->as, emit->exit_label); + + // Label re-entry point + mp_asm_base_label_assign(&emit->as->base, *emit->label_slot); + + // Re-open any active exception handler + if (emit->exc_stack_size > 0) { + // Find innermost active exception handler, to restore as current handler + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + for (; e >= emit->exc_stack; --e) { + if (e->is_active) { + // Found active handler, get its PC + ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_RET); + } + } + } + + emit_native_adjust_stack_size(emit, 1); // send_value + + if (kind == MP_EMIT_YIELD_VALUE) { + // Check LOCAL_IDX_EXC_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); + emit_call(emit, MP_F_NATIVE_RAISE); + } else { + // Label loop entry + emit_native_label_assign(emit, *emit->label_slot + 2); + + // Get the next item from the delegate generator + vtype_kind_t vtype; + emit_pre_pop_reg(emit, &vtype, REG_ARG_2); // send_value + emit_access_stack(emit, 1, &vtype, REG_ARG_1); // generator + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_3, LOCAL_IDX_EXC_VAL(emit)); // throw_value + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_3); + emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, 1); // ret_value + emit_call(emit, MP_F_NATIVE_YIELD_FROM); + + // If returned non-zero then generator continues + ASM_JUMP_IF_REG_NONZERO(emit->as, REG_RET, *emit->label_slot + 1, true); + + // Pop exhausted gen, replace with ret_value + emit_native_adjust_stack_size(emit, 1); // ret_value + emit_fold_stack_top(emit, REG_ARG_1); + } } STATIC void emit_native_start_except_handler(emit_t *emit) { - // This instruction follows an nlr_pop, so the stack counter is back to zero, when really - // it should be up by a whole nlr_buf_t. We then want to pop the nlr_buf_t here, but save - // the first 2 elements, so we can get the thrown value. - adjust_stack(emit, 1); - vtype_kind_t vtype_nlr; - emit_pre_pop_reg(emit, &vtype_nlr, REG_ARG_1); // get the thrown value - emit_pre_pop_discard(emit); // discard the linked-list pointer in the nlr_buf - emit_post_push_reg_reg_reg(emit, VTYPE_PYOBJ, REG_ARG_1, VTYPE_PYOBJ, REG_ARG_1, VTYPE_PYOBJ, REG_ARG_1); // push the 3 exception items + // Protected block has finished so leave the current exception handler + emit_native_leave_exc_stack(emit, true); + + // Get and push nlr_buf.ret_val + ASM_MOV_REG_LOCAL(emit->as, REG_TEMP0, LOCAL_IDX_EXC_VAL(emit)); + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_TEMP0); } STATIC void emit_native_end_except_handler(emit_t *emit) { - adjust_stack(emit, -1); + adjust_stack(emit, -1); // pop the exception (end_finally didn't use it) } const emit_method_table_t EXPORT_FUN(method_table) = { - emit_native_set_native_type, emit_native_start_pass, emit_native_end_pass, emit_native_last_emit_was_return_value, diff --git a/py/emitnthumb.c b/py/emitnthumb.c index 2b68ca3a13f71..1c33e7a68b59e 100644 --- a/py/emitnthumb.c +++ b/py/emitnthumb.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmthumb.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (3) // r4 +#define NLR_BUF_IDX_LOCAL_2 (4) // r5 +#define NLR_BUF_IDX_LOCAL_3 (5) // r6 + #define N_THUMB (1) #define EXPORT_FUN(name) emit_native_thumb_##name #include "py/emitnative.c" diff --git a/py/emitnx64.c b/py/emitnx64.c index b9800f636e087..4abb3ecad3a32 100644 --- a/py/emitnx64.c +++ b/py/emitnx64.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmx64.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (5) // rbx +#define NLR_BUF_IDX_LOCAL_2 (6) // r12 +#define NLR_BUF_IDX_LOCAL_3 (7) // r13 + #define N_X64 (1) #define EXPORT_FUN(name) emit_native_x64_##name #include "py/emitnative.c" diff --git a/py/emitnx86.c b/py/emitnx86.c index 5d2bbb267a166..7c96c3b82b352 100644 --- a/py/emitnx86.c +++ b/py/emitnx86.c @@ -9,10 +9,16 @@ #define GENERIC_ASM_API (1) #include "py/asmx86.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (5) // ebx +#define NLR_BUF_IDX_LOCAL_2 (7) // esi +#define NLR_BUF_IDX_LOCAL_3 (6) // edi + // x86 needs a table to know how many args a given function has STATIC byte mp_f_n_args[MP_F_NUMBER_OF] = { [MP_F_CONVERT_OBJ_TO_NATIVE] = 2, [MP_F_CONVERT_NATIVE_TO_OBJ] = 2, + [MP_F_NATIVE_SWAP_GLOBALS] = 1, [MP_F_LOAD_NAME] = 1, [MP_F_LOAD_GLOBAL] = 1, [MP_F_LOAD_BUILD_CLASS] = 0, @@ -56,9 +62,11 @@ STATIC byte mp_f_n_args[MP_F_NUMBER_OF] = { [MP_F_DELETE_GLOBAL] = 1, [MP_F_NEW_CELL] = 1, [MP_F_MAKE_CLOSURE_FROM_RAW_CODE] = 3, - [MP_F_SETUP_CODE_STATE] = 5, + [MP_F_ARG_CHECK_NUM_SIG] = 3, + [MP_F_SETUP_CODE_STATE] = 4, [MP_F_SMALL_INT_FLOOR_DIVIDE] = 2, [MP_F_SMALL_INT_MODULO] = 2, + [MP_F_NATIVE_YIELD_FROM] = 3, }; #define N_X86 (1) diff --git a/py/emitnxtensa.c b/py/emitnxtensa.c index 1a423e21eba3e..34089e90dc27b 100644 --- a/py/emitnxtensa.c +++ b/py/emitnxtensa.c @@ -8,6 +8,11 @@ #define GENERIC_ASM_API (1) #include "py/asmxtensa.h" +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (8) // a12 +#define NLR_BUF_IDX_LOCAL_2 (9) // a13 +#define NLR_BUF_IDX_LOCAL_3 (10) // a14 + #define N_XTENSA (1) #define EXPORT_FUN(name) emit_native_xtensa_##name #include "py/emitnative.c" diff --git a/py/enum.c b/py/enum.c index 02a85a168c805..8dc83a9fba653 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 708678eb699b2..286bac098fa44 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 166a98a2e6385..f8d06d2d715be 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 0e040a44fd742..6f8191d3110a5 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 3ba1b590d71ea..668b7ac17e9cd 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 69327060f74c7..c29624c3afd89 --- 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,14 +185,14 @@ 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); } void gc_deinit(void) { - // Run any finalizers before we stop using the heap. + // Run any finalisers before we stop using the heap. gc_sweep_all(); MP_STATE_MEM(gc_pool_start) = 0; @@ -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 } @@ -480,7 +480,8 @@ bool gc_alloc_possible(void) { // We place long lived objects at the end of the heap rather than the start. This reduces // fragmentation by localizing the heap churn to one portion of memory (the start of the heap.) -void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived) { +void *gc_alloc(size_t n_bytes, unsigned int alloc_flags, bool long_lived) { + bool has_finaliser = alloc_flags & GC_ALLOC_FLAG_HAS_FINALISER; size_t n_blocks = ((n_bytes + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1))) / BYTES_PER_BLOCK; DEBUG_printf("gc_alloc(" UINT_FMT " bytes -> " UINT_FMT " blocks)\n", n_bytes, n_blocks); @@ -549,7 +550,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 +613,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 +631,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 +755,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 +765,9 @@ bool gc_has_finaliser(const void *ptr) { // invalid pointer GC_EXIT(); -#else - (void) ptr; -#endif + #else + (void)ptr; + #endif return false; } @@ -782,7 +783,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 +809,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 +862,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 +934,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 +990,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 +1000,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 +1019,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 +1051,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 +1087,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 +1141,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); } @@ -1134,7 +1154,8 @@ void gc_dump_alloc_table(void) { GC_EXIT(); } -#if DEBUG_PRINT +#if 0 +// For testing the GC functions void gc_test(void) { mp_uint_t len = 500; mp_uint_t *heap = malloc(len); @@ -1151,11 +1172,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 +1184,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 b7c2889d5c597..0cc432b94efaa 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); @@ -60,11 +60,15 @@ void gc_collect_end(void); // Is the gc heap available? bool gc_alloc_possible(void); -void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived); // Use this function to sweep the whole heap and run all finalisers void gc_sweep_all(void); +enum { + GC_ALLOC_FLAG_HAS_FINALISER = 1, +}; + +void *gc_alloc(size_t n_bytes, unsigned int alloc_flags, bool long_lived); void gc_free(void *ptr); // does not call finaliser size_t gc_nbytes(const void *ptr); bool gc_has_finaliser(const void *ptr); diff --git a/py/gc_long_lived.c b/py/gc_long_lived.c old mode 100755 new mode 100644 index 0e94390e9dfed..8ee8a4a4e1025 --- 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 5b195d23e4265..a3ac87128f36f 100644 --- a/py/genlast.py +++ b/py/genlast.py @@ -12,8 +12,9 @@ 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 de121f87a2149..834a8d62e3198 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 74195fe030523..dab34294a43ad 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 18d327f002971..7745607131ff4 100644 --- a/py/makemoduledefs.py +++ b/py/makemoduledefs.py @@ -12,14 +12,11 @@ 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 b4f4f1b0358e5..6a6125fe206ae 100644 --- a/py/makeqstrdata.py +++ b/py/makeqstrdata.py @@ -12,14 +12,13 @@ import re import sys -from math import log 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 +31,44 @@ # - 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 +78,8 @@ "\r": "\\r", "\t": "\\t", "\v": "\\v", - "\'": "\\'", - "\"": "\\\"" + "'": "\\'", + '"': '\\"', } # this must match the equivalent function in qstr.c @@ -90,6 +90,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 +106,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 +136,7 @@ def iter(self, text): 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 +144,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 @@ -162,7 +166,7 @@ def compute_huffman_coding(translations, compression_filename): sum_len = 0 while True: # Until the dictionary is filled to capacity, use a heuristic to find - # the best "word" (2- to 9-gram) to add to it. + # the best "word" (3- to 9-gram) to add to it. # # The TextSplitter allows us to avoid considering parts of the text # that are already covered by a previously chosen word, for example @@ -174,35 +178,25 @@ def compute_huffman_coding(translations, compression_filename): for t in texts: for (found, word) in extractor.iter_words(t): if not found: - for substr in iter_substrings(word, minlen=2, maxlen=9): + for substr in iter_substrings(word, minlen=3, maxlen=9): counter[substr] += 1 # 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) ** (occ + 4)) for (s, occ) in counter.items() if occ > 4), key=lambda x: x[1], reverse=True, ) - # Do we have a "word" that occurred 5 times and got a score of at least - # 5? Horray. Pick the one with the highest score. - word = None - for (s, score, occ) in scores: - if occ < 5: - continue - if score < 5: - break - word = s + # Pick the one with the highest score. + if not scores: break + word = scores[0][0] + # If we can successfully add it to the dictionary, do so. Otherwise, # we've filled the dictionary to capacity and are done. - if not word: - break if sum_len + len(word) - 2 > max_words_len: break if len(words) == max_words: @@ -234,8 +228,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 +251,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 +260,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 +325,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 +333,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 +371,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 +390,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 +418,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 +448,67 @@ def parse_input_headers(infiles): return qcfgs, qstrs, i18ns -def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): - 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): +def escape_bytes(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 + return qstr else: # qstr contains non-printable codes so render entire thing as hex pairs - qdata = ''.join(('\\x%02x' % b) for b in qbytes) + qbytes = bytes_cons(qstr, "utf8") + return "".join(("\\x%02x" % b) for b in qbytes) + +def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): + qbytes = bytes_cons(qstr, "utf8") + qlen = len(qbytes) + qhash = compute_hash(qbytes, cfg_bytes_hash) 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)) - return '(const byte*)"%s%s" "%s"' % (qhash_str, qlen_str, qdata) + qdata = escape_bytes(qstr) + return '%d, %d, "%s"' % (qhash, qlen, 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, 0, 0, "")') 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 +517,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 d3e90ba486133..e6c003311367a 100644 --- a/py/makeqstrdefs.py +++ b/py/makeqstrdefs.py @@ -15,51 +15,54 @@ # - 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 7ceeaeaddedf7..41e5956542959 100644 --- a/py/makeversionhdr.py +++ b/py/makeversionhdr.py @@ -11,6 +11,7 @@ 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 8d5141ee0463a..5c09a2d283e9b 100644 --- a/py/malloc.c +++ b/py/malloc.c @@ -57,11 +57,18 @@ #undef free #undef realloc #define malloc_ll(b, ll) gc_alloc((b), false, (ll)) -#define malloc_with_finaliser(b) gc_alloc((b), true, false) +#define malloc_with_finaliser(b, ll) gc_alloc((b), true, (ll)) #define free gc_free #define realloc(ptr, n) gc_realloc(ptr, n, true) #define realloc_ext(ptr, n, mv) gc_realloc(ptr, n, mv) #else + +// GC is disabled. Use system malloc/realloc/free. + +#if MICROPY_ENABLE_FINALISER +#error MICROPY_ENABLE_FINALISER requires MICROPY_ENABLE_GC +#endif + #define malloc_ll(b, ll) malloc(b) #define malloc_with_finaliser(b) malloc((b)) @@ -75,6 +82,7 @@ STATIC void *realloc_ext(void *ptr, size_t n_bytes, bool allow_move) { return NULL; } } + #endif // MICROPY_ENABLE_GC void *m_malloc(size_t num_bytes, bool long_lived) { @@ -82,37 +90,37 @@ 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; } #if MICROPY_ENABLE_FINALISER -void *m_malloc_with_finaliser(size_t num_bytes) { - void *ptr = malloc_with_finaliser(num_bytes); +void *m_malloc_with_finaliser(size_t num_bytes, bool long_lived) { + void *ptr = malloc_with_finaliser(num_bytes, 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 +139,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 +154,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 +167,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 +182,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 +195,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 69eed9d3b9ec9..06695c8de814d 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); @@ -425,13 +425,13 @@ void mp_set_clear(mp_set_t *set) { #if defined(DEBUG_PRINT) && DEBUG_PRINT void mp_map_dump(mp_map_t *map) { for (size_t i = 0; i < map->alloc; i++) { - if (map->table[i].key != NULL) { + if (map->table[i].key != MP_OBJ_NULL) { mp_obj_print(map->table[i].key, PRINT_REPR); } else { - printf("(nil)"); + DEBUG_printf("(nil)"); } - printf(": %p\n", map->table[i].value); + DEBUG_printf(": %p\n", map->table[i].value); } - printf("---\n"); + DEBUG_printf("---\n"); } #endif diff --git a/py/misc.h b/py/misc.h index 6ed256e705f5a..acb0d50cec7df 100644 --- a/py/misc.h +++ b/py/misc.h @@ -55,37 +55,46 @@ typedef unsigned int uint; // Static assertion macro #define MP_STATIC_ASSERT(cond) ((void)sizeof(char[1 - 2 * !(cond)])) +// Explicit fallthrough delcarations for case statements +#ifdef __GNUC__ +#define FALLTHROUGH __attribute__((fallthrough)) +#else +#define FALLTHROUGH ((void)0) /* FALLTHROUGH */ +#endif + /** memory allocation ******************************************/ // 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)))) -#define m_new_obj_var_with_finaliser(type, var_type, var_num) ((type*)m_malloc_with_finaliser(sizeof(type) + sizeof(var_type) * (var_num))) +#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 @@ -93,7 +102,7 @@ typedef unsigned int uint; void *m_malloc(size_t num_bytes, bool long_lived); void *m_malloc_maybe(size_t num_bytes, bool long_lived); -void *m_malloc_with_finaliser(size_t num_bytes); +void *m_malloc_with_finaliser(size_t num_bytes, bool long_lived); void *m_malloc0(size_t num_bytes, bool long_lived); #if MICROPY_MALLOC_USES_ALLOCATED_SIZE void *m_realloc(void *ptr, size_t old_num_bytes, size_t new_num_bytes); @@ -118,7 +127,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)) @@ -138,9 +147,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); @@ -177,9 +193,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); @@ -200,10 +222,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/mkrules.mk b/py/mkrules.mk index 549b0e5e42d6c..2721d293e0261 100644 --- a/py/mkrules.mk +++ b/py/mkrules.mk @@ -107,7 +107,7 @@ endif ifneq ($(FROZEN_MPY_DIRS),) # to build the MicroPython cross compiler # Currently not used, because the wrong mpy-cross may be left over from a previous build. Build by hand to make sure. -$(MPY_CROSS): $(TOP)/py/*.[ch] $(TOP)/mpy-cross/*.[ch] $(TOP)/ports/windows/fmode.c +$(MPY_CROSS): $(TOP)/py/*.[ch] $(TOP)/mpy-cross/*.[ch] $(TOP)/mpy-cross/fmode.c $(Q)$(MAKE) -C $(TOP)/mpy-cross # Copy all the modules and single python files to freeze to a common area, omitting top-level dirs (the repo names). diff --git a/py/modarray.c b/py/modarray.c index 75bc5169f8ef0..a47684bf97c1e 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 fe3c366eec50a..49d88f728eeae 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)")); } @@ -219,7 +220,12 @@ STATIC mp_obj_t mp_builtin_hash(mp_obj_t o_in) { MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hash_obj, mp_builtin_hash); STATIC mp_obj_t mp_builtin_hex(mp_obj_t o_in) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_x), o_in); + #else + mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR__brace_open__colon__hash_x_brace_close_), o_in }; + return mp_obj_str_format(MP_ARRAY_SIZE(args), args, NULL); + #endif } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hex_obj, mp_builtin_hex); @@ -324,13 +330,18 @@ STATIC mp_obj_t mp_builtin_next(mp_obj_t o) { MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_next_obj, mp_builtin_next); STATIC mp_obj_t mp_builtin_oct(mp_obj_t o_in) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_o), o_in); + #else + mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR__brace_open__colon__hash_o_brace_close_), o_in }; + return mp_obj_str_format(MP_ARRAY_SIZE(args), args, NULL); + #endif } 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 +358,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 +476,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 +494,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 +505,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 +742,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 +773,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 d6b364733d8e6..63f289d4981be 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 9634c5ce736d1..235745f5843d9 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 b01876422aed2..e655cfa93e010 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 4bcc3971eb6c0..e88a9b04f3ae4 100644 --- a/py/modio.c +++ b/py/modio.c @@ -44,7 +44,7 @@ extern const mp_obj_type_t mp_type_textio; STATIC const mp_obj_type_t mp_type_iobase; -STATIC mp_obj_base_t iobase_singleton = {&mp_type_iobase}; +STATIC const mp_obj_base_t iobase_singleton = {&mp_type_iobase}; STATIC mp_obj_t iobase_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { (void)type; @@ -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 ec520bb6f21b2..9df345a564c0d 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)); @@ -238,6 +238,70 @@ STATIC mp_obj_t mp_math_degrees(mp_obj_t x_obj) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_degrees_obj, mp_math_degrees); +#if MICROPY_PY_MATH_FACTORIAL + +#if MICROPY_OPT_MATH_FACTORIAL + +// factorial(x): slightly efficient recursive implementation +STATIC mp_obj_t mp_math_factorial_inner(mp_uint_t start, mp_uint_t end) { + if (start == end) { + return mp_obj_new_int(start); + } else if (end - start == 1) { + return mp_binary_op(MP_BINARY_OP_MULTIPLY, MP_OBJ_NEW_SMALL_INT(start), MP_OBJ_NEW_SMALL_INT(end)); + } else if (end - start == 2) { + mp_obj_t left = MP_OBJ_NEW_SMALL_INT(start); + mp_obj_t middle = MP_OBJ_NEW_SMALL_INT(start + 1); + mp_obj_t right = MP_OBJ_NEW_SMALL_INT(end); + mp_obj_t tmp = mp_binary_op(MP_BINARY_OP_MULTIPLY, left, middle); + return mp_binary_op(MP_BINARY_OP_MULTIPLY, tmp, right); + } else { + mp_uint_t middle = start + ((end - start) >> 1); + mp_obj_t left = mp_math_factorial_inner(start, middle); + mp_obj_t right = mp_math_factorial_inner(middle + 1, end); + return mp_binary_op(MP_BINARY_OP_MULTIPLY, left, right); + } +} +STATIC mp_obj_t mp_math_factorial(mp_obj_t x_obj) { + mp_int_t max = mp_obj_get_int(x_obj); + if (max < 0) { + mp_raise_msg(&mp_type_ValueError, translate("negative factorial")); + } else if (max == 0) { + return MP_OBJ_NEW_SMALL_INT(1); + } + return mp_math_factorial_inner(1, max); +} + +#else + +// factorial(x): squared difference implementation +// based on http://www.luschny.de/math/factorial/index.html +STATIC mp_obj_t mp_math_factorial(mp_obj_t x_obj) { + mp_int_t max = mp_obj_get_int(x_obj); + if (max < 0) { + mp_raise_msg(&mp_type_ValueError, translate("negative factorial")); + } else if (max <= 1) { + return MP_OBJ_NEW_SMALL_INT(1); + } + mp_int_t h = max >> 1; + mp_int_t q = h * h; + mp_int_t r = q << 1; + if (max & 1) { + r *= max; + } + mp_obj_t prod = MP_OBJ_NEW_SMALL_INT(r); + for (mp_int_t num = 1; num < max - 2; num += 2) { + q -= num; + prod = mp_binary_op(MP_BINARY_OP_MULTIPLY, prod, MP_OBJ_NEW_SMALL_INT(q)); + } + return prod; +} + +#endif + +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_factorial_obj, mp_math_factorial); + +#endif + STATIC const mp_rom_map_elem_t mp_module_math_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_math) }, { MP_ROM_QSTR(MP_QSTR_e), mp_const_float_e }, @@ -280,6 +344,9 @@ STATIC const mp_rom_map_elem_t mp_module_math_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_trunc), MP_ROM_PTR(&mp_math_trunc_obj) }, { MP_ROM_QSTR(MP_QSTR_radians), MP_ROM_PTR(&mp_math_radians_obj) }, { MP_ROM_QSTR(MP_QSTR_degrees), MP_ROM_PTR(&mp_math_degrees_obj) }, + #if MICROPY_PY_MATH_FACTORIAL + { MP_ROM_QSTR(MP_QSTR_factorial), MP_ROM_PTR(&mp_math_factorial_obj) }, + #endif #if MICROPY_PY_MATH_SPECIAL_FUNCTIONS { MP_ROM_QSTR(MP_QSTR_erf), MP_ROM_PTR(&mp_math_erf_obj) }, { MP_ROM_QSTR(MP_QSTR_erfc), MP_ROM_PTR(&mp_math_erfc_obj) }, @@ -292,7 +359,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 7e29825ae4391..4cd9160bd0885 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 7675de275d46c..8f78fa234ae25 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); @@ -214,9 +214,11 @@ STATIC void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, c p += cnt; } else { while (cnt--) { - mp_binary_set_val(fmt_type, *fmt, args[i], &p); // Pad bytes don't have a corresponding argument. - if (*fmt != 'x') { + if (*fmt == 'x') { + mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p); + } else { + mp_binary_set_val(fmt_type, *fmt, args[i], &p); i++; } } @@ -229,7 +231,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 +277,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 81628683d8e5f..9cbc5e314c96b 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 250756ef27e94..89b4f3fb66888 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 3928f8cd894ba..6ead6a8054abb 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 034d39d409f86..6badacaf6c763 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -111,6 +111,15 @@ #define MICROPY_ALLOC_GC_STACK_SIZE (64) #endif +// The C-type to use for entries in the GC stack. By default it allows the +// heap to be as large as the address space, but the bit-width of this type can +// be reduced to save memory when the heap is small enough. The type must be +// big enough to index all blocks in the heap, which is set by +// heap-size-in-bytes / MICROPY_BYTES_PER_GC_BLOCK. +#ifndef MICROPY_GC_STACK_ENTRY_TYPE +#define MICROPY_GC_STACK_ENTRY_TYPE size_t +#endif + // Be conservative and always clear to zero newly (re)allocated memory in the GC. // This helps eliminate stray pointers that hold on to memory that's no longer // used. It decreases performance due to unnecessary memory clearing. @@ -390,6 +399,11 @@ #define MICROPY_MEM_STATS (0) #endif +// The mp_print_t printer used for debugging output +#ifndef MICROPY_DEBUG_PRINTER +#define MICROPY_DEBUG_PRINTER (&mp_plat_print) +#endif + // Whether to build functions that print debugging info: // mp_bytecode_print // mp_parse_node_print @@ -402,6 +416,11 @@ #define MICROPY_DEBUG_VERBOSE (0) #endif +// Whether to enable a simple VM stack overflow check +#ifndef MICROPY_DEBUG_VM_STACK_OVERFLOW +#define MICROPY_DEBUG_VM_STACK_OVERFLOW (0) +#endif + /*****************************************************************************/ /* Optimisations */ @@ -413,6 +432,14 @@ #define MICROPY_OPT_COMPUTED_GOTO (0) #endif +// Whether to save trade flash space for speed in MICROPY_OPT_COMPUTED_GOTO. +// Costs about 3% speed, saves about 1500 bytes space. In addition to the assumptions +// of MICROPY_OPT_COMPUTED_GOTO, also assumes that mp_execute_bytecode is less than +// 32kB in size. +#ifndef MICROPY_OPT_COMPUTED_GOTO_SAVE_SPACE +#define MICROPY_OPT_COMPUTED_GOTO_SAVE_SPACE (0) +#endif + // Whether to cache result of map lookups in LOAD_NAME, LOAD_GLOBAL, LOAD_ATTR, // STORE_ATTR bytecodes. Uses 1 byte extra RAM for each of these opcodes and // uses a bit of extra code ROM, but greatly improves lookup speed. @@ -426,6 +453,12 @@ #define MICROPY_OPT_MPZ_BITWISE (0) #endif + +// Whether math.factorial is large, fast and recursive (1) or small and slow (0). +#ifndef MICROPY_OPT_MATH_FACTORIAL +#define MICROPY_OPT_MATH_FACTORIAL (0) +#endif + /*****************************************************************************/ /* Python internal features */ @@ -504,9 +537,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 @@ -656,6 +689,11 @@ typedef double mp_float_t; #define MICROPY_MODULE_BUILTIN_INIT (0) #endif +// Whether to support module-level __getattr__ (see PEP 562) +#ifndef MICROPY_MODULE_GETATTR +#define MICROPY_MODULE_GETATTR (0) +#endif + // Whether module weak links are supported #ifndef MICROPY_MODULE_WEAK_LINKS #define MICROPY_MODULE_WEAK_LINKS (0) @@ -788,6 +826,16 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_STR_CENTER (0) #endif +// Whether str.count() method provided +#ifndef MICROPY_PY_BUILTINS_STR_COUNT +#define MICROPY_PY_BUILTINS_STR_COUNT (1) +#endif + +// Whether str % (...) formatting operator provided +#ifndef MICROPY_PY_BUILTINS_STR_OP_MODULO +#define MICROPY_PY_BUILTINS_STR_OP_MODULO (1) +#endif + // Whether str.partition()/str.rpartition() method provided #ifndef MICROPY_PY_BUILTINS_STR_PARTITION #define MICROPY_PY_BUILTINS_STR_PARTITION (0) @@ -803,6 +851,11 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_BYTEARRAY (1) #endif +// Whether to support dict.fromkeys() class method +#ifndef MICROPY_PY_BUILTINS_DICT_FROMKEYS +#define MICROPY_PY_BUILTINS_DICT_FROMKEYS (1) +#endif + // Whether to support memoryview object #ifndef MICROPY_PY_BUILTINS_MEMORYVIEW #define MICROPY_PY_BUILTINS_MEMORYVIEW (0) @@ -1018,6 +1071,11 @@ typedef double mp_float_t; #define MICROPY_PY_MATH_SPECIAL_FUNCTIONS (0) #endif +// Whether to provide math.factorial function +#ifndef MICROPY_PY_MATH_FACTORIAL +#define MICROPY_PY_MATH_FACTORIAL (0) +#endif + // Whether to provide "cmath" module #ifndef MICROPY_PY_CMATH #define MICROPY_PY_CMATH (0) @@ -1170,6 +1228,12 @@ typedef double mp_float_t; #define MICROPY_PY_UCTYPES (0) #endif +// Whether to provide SHORT, INT, LONG, etc. types in addition to +// exact-bitness types like INT16, INT32, etc. +#ifndef MICROPY_PY_UCTYPES_NATIVE_C_TYPES +#define MICROPY_PY_UCTYPES_NATIVE_C_TYPES (1) +#endif + #ifndef MICROPY_PY_UZLIB #define MICROPY_PY_UZLIB (0) #endif @@ -1211,6 +1275,10 @@ typedef double mp_float_t; #define MICROPY_PY_UHASHLIB (0) #endif +#ifndef MICROPY_PY_UHASHLIB_MD5 +#define MICROPY_PY_UHASHLIB_MD5 (0) +#endif + #ifndef MICROPY_PY_UHASHLIB_SHA1 #define MICROPY_PY_UHASHLIB_SHA1 (0) #endif @@ -1219,6 +1287,14 @@ typedef double mp_float_t; #define MICROPY_PY_UHASHLIB_SHA256 (1) #endif +#ifndef MICROPY_PY_UCRYPTOLIB +#define MICROPY_PY_UCRYPTOLIB (0) +#endif + +#ifndef MICROPY_PY_UCRYPTOLIB_CONSTS +#define MICROPY_PY_UCRYPTOLIB_CONSTS (0) +#endif + #ifndef MICROPY_PY_UBINASCII #define MICROPY_PY_UBINASCII (0) #endif @@ -1362,7 +1438,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) @@ -1425,7 +1501,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 @@ -1468,21 +1544,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 e339fde85258d..02c618958a23a 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 e814d2ebe527b..032ce8e97bc1b 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 0d12b9a3d03e6..4458ea883bcab 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 32f353528c29e..0c57563acc531 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -79,7 +79,7 @@ typedef struct _mp_state_mem_t { void *gc_lowest_long_lived_ptr; int gc_stack_overflow; - size_t gc_stack[MICROPY_ALLOC_GC_STACK_SIZE]; + MICROPY_GC_STACK_ENTRY_TYPE gc_stack[MICROPY_ALLOC_GC_STACK_SIZE]; uint16_t gc_lock_depth; // This variable controls auto garbage collection. If set to false then the @@ -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 @@ -197,7 +197,7 @@ typedef struct _mp_state_vm_t { // pointer and sizes to store interned string data // (qstr_last_chunk can be root pointer but is also stored in qstr pool) - byte *qstr_last_chunk; + char *qstr_last_chunk; size_t qstr_last_alloc; size_t qstr_last_used; @@ -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 3a6983e9d0c00..bd023e62797f5 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 41b46f92ffc73..248d0ec359c5d 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) { + 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; + if (z->len != 1) { + return 1; + } cmp = z->dig[0] - sml_int; } else { - if (sml_int > 0) return -1; + 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; + 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 ade04a4f7ca19..6b941cb7b90bf 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 9ac8060097ff3..7662aaeaf6b1e 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); @@ -83,6 +89,20 @@ mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type) { #if MICROPY_EMIT_NATIVE +mp_obj_dict_t *mp_native_swap_globals(mp_obj_dict_t *new_globals) { + if (new_globals == NULL) { + // Globals were the originally the same so don't restore them + return NULL; + } + mp_obj_dict_t *old_globals = mp_globals_get(); + if (old_globals == new_globals) { + // Don't set globals if they are the same, and return NULL to indicate this + return NULL; + } + mp_globals_set(new_globals); + return old_globals; +} + // wrapper that accepts n_args and n_kw in one argument // (native emitter can only pass at most 3 arguments to a function) mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const mp_obj_t *args) { @@ -92,7 +112,7 @@ mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const m // wrapper that makes raise obj and raises it // END_FINALLY opcode requires that we don't raise if o==None void mp_native_raise(mp_obj_t o) { - if (o != mp_const_none) { + if (o != MP_OBJ_NULL && o != mp_const_none) { nlr_raise(mp_make_raise_obj(o)); } } @@ -123,10 +143,50 @@ STATIC mp_obj_t mp_native_iternext(mp_obj_iter_buf_t *iter) { return mp_iternext(obj); } +STATIC bool mp_native_yield_from(mp_obj_t gen, mp_obj_t send_value, mp_obj_t *ret_value) { + mp_vm_return_kind_t ret_kind; + nlr_buf_t nlr_buf; + mp_obj_t throw_value = *ret_value; + if (nlr_push(&nlr_buf) == 0) { + if (throw_value != MP_OBJ_NULL) { + send_value = MP_OBJ_NULL; + } + ret_kind = mp_resume(gen, send_value, throw_value, ret_value); + nlr_pop(); + } else { + ret_kind = MP_VM_RETURN_EXCEPTION; + *ret_value = nlr_buf.ret_val; + } + + if (ret_kind == MP_VM_RETURN_YIELD) { + return true; + } else if (ret_kind == MP_VM_RETURN_NORMAL) { + if (*ret_value == MP_OBJ_STOP_ITERATION) { + *ret_value = mp_const_none; + } + } else { + assert(ret_kind == MP_VM_RETURN_EXCEPTION); + if (!mp_obj_exception_match(*ret_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + nlr_raise(*ret_value); + } + *ret_value = mp_obj_exception_get_value(*ret_value); + } + + if (throw_value != MP_OBJ_NULL && mp_obj_exception_match(throw_value, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { + nlr_raise(mp_make_raise_obj(throw_value)); + } + + return false; +} + // these must correspond to the respective enum in runtime0.h -void *const mp_fun_table[MP_F_NUMBER_OF] = { +const void *const mp_fun_table[MP_F_NUMBER_OF] = { + &mp_const_none_obj, + &mp_const_false_obj, + &mp_const_true_obj, mp_convert_obj_to_native, mp_convert_native_to_obj, + mp_native_swap_globals, mp_load_name, mp_load_global, mp_load_build_class, @@ -145,10 +205,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,18 +221,20 @@ 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, mp_delete_global, mp_obj_new_cell, mp_make_closure_from_raw_code, + mp_arg_check_num_sig, mp_setup_code_state, mp_small_int_floor_divide, mp_small_int_modulo, + mp_native_yield_from, }; /* diff --git a/py/nlr.c b/py/nlr.c index 95d833177d308..6dfd16219619b 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 aed24e277a5b7..00f10b75fd4e6 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 464995fa8826c..1cdc2f063cf35 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 246d6a95b8b80..d9ef0d8138271 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 18306253d75ac..598b199c2941b 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 e04535ff83222..5aa767aaeb648 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 5f19089e85097..6b2dded57e9f0 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 } @@ -267,12 +269,8 @@ mp_int_t mp_obj_get_int(mp_const_obj_t arg) { } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { 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); - #else - mp_raise_TypeError_varg( - translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_int); - #endif + mp_obj_t res = mp_unary_op(MP_UNARY_OP_INT, (mp_obj_t)arg); + return mp_obj_int_get_checked(res); } } @@ -331,10 +329,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 +362,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 +380,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 +394,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 +409,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 +429,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 +464,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 +477,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 +507,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 +563,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 +591,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 066562cc43549..4e32ce8b0ee41 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,25 @@ 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)) +#if MICROPY_PY_BUILTINS_FLOAT #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; @@ -161,28 +170,38 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } num = {.f = f}; return (mp_obj_t)(((num.u & ~0x3) | 2) + 0x80800000); } +#endif -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 (((uint64_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 (((uint64_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)) #if MICROPY_PY_BUILTINS_FLOAT + +#if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_DOUBLE +#error MICROPY_OBJ_REPR_D requires MICROPY_FLOAT_IMPL_DOUBLE +#endif + #define mp_const_float_e {((mp_obj_t)((uint64_t)0x4005bf0a8b145769 + 0x8004000000000000))} #define mp_const_float_pi {((mp_obj_t)((uint64_t)0x400921fb54442d18 + 0x8004000000000000))} @@ -205,13 +224,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 +252,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 +280,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 @@ -274,27 +297,31 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; #define MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name) extern const mp_obj_fun_builtin_var_t obj_name #define MP_DECLARE_CONST_FUN_OBJ_KW(obj_name) extern const mp_obj_fun_builtin_var_t obj_name +#define MP_OBJ_FUN_ARGS_MAX (0xffff) // to set maximum value in n_args_max below +#define MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw) ((uint32_t)((((uint32_t)(n_args_min)) << 17) | (((uint32_t)(n_args_max)) << 1) | ((takes_kw) ? 1 : 0))) + #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}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .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}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .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}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .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 +340,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 +352,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 +433,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 +454,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 +506,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 @@ -590,6 +621,8 @@ extern const mp_obj_type_t mp_type_slice; extern const mp_obj_type_t mp_type_zip; extern const mp_obj_type_t mp_type_array; extern const mp_obj_type_t mp_type_super; +extern const mp_obj_type_t mp_type_gen_wrap; +extern const mp_obj_type_t mp_type_native_gen_wrap; extern const mp_obj_type_t mp_type_gen_instance; extern const mp_obj_type_t mp_type_fun_builtin_0; extern const mp_obj_type_t mp_type_fun_builtin_1; @@ -597,6 +630,9 @@ extern const mp_obj_type_t mp_type_fun_builtin_2; extern const mp_obj_type_t mp_type_fun_builtin_3; extern const mp_obj_type_t mp_type_fun_builtin_var; extern const mp_obj_type_t mp_type_fun_bc; +#if MICROPY_EMIT_NATIVE +extern const mp_obj_type_t mp_type_fun_native; +#endif extern const mp_obj_type_t mp_type_module; extern const mp_obj_type_t mp_type_staticmethod; extern const mp_obj_type_t mp_type_classmethod; @@ -665,17 +701,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); @@ -684,6 +722,7 @@ mp_obj_t mp_obj_new_bytearray_by_ref(size_t n, void *items); mp_obj_t mp_obj_new_int_from_float(mp_float_t val); mp_obj_t mp_obj_new_complex(mp_float_t real, mp_float_t imag); extern mp_float_t uint64_to_float(uint64_t ui64); +extern uint64_t float_to_uint64(float f); #endif mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type); mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg); @@ -722,7 +761,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); @@ -731,7 +772,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); @@ -779,7 +820,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 @@ -814,7 +857,9 @@ size_t mp_obj_dict_len(mp_obj_t self_in); mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index); mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value); mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key); -mp_map_t *mp_obj_dict_get_map(mp_obj_t self_in); +static inline mp_map_t *mp_obj_dict_get_map(mp_obj_t dict) { + return &((mp_obj_dict_t *)MP_OBJ_TO_PTR(dict))->map; +} // set void mp_obj_set_store(mp_obj_t self_in, mp_obj_t item); @@ -834,12 +879,9 @@ typedef struct _mp_obj_fun_builtin_fixed_t { } fun; } mp_obj_fun_builtin_fixed_t; -#define MP_OBJ_FUN_ARGS_MAX (0xffff) // to set maximum value in n_args_max below typedef struct _mp_obj_fun_builtin_var_t { mp_obj_base_t base; - bool is_kw : 1; - mp_uint_t n_args_min : 15; // inclusive - mp_uint_t n_args_max : 16; // inclusive + uint32_t sig; // see MP_OBJ_FUN_MAKE_SIG union { mp_fun_var_t var; mp_fun_kw_t kw; @@ -905,17 +947,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 e0b4cbd55fffb..7864d79867c8f 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -52,11 +52,14 @@ // Note that we don't handle the case where the original buffer might change // size due to a resize of the original parent object. -// make (& TYPECODE_MASK) a null operation if memorview not enabled #if MICROPY_PY_BUILTINS_MEMORYVIEW #define TYPECODE_MASK (0x7f) +#define memview_offset free #else +// make (& TYPECODE_MASK) a null operation if memorview not enabled #define TYPECODE_MASK (~(size_t)0) +// memview_offset should not be accessed if memoryview is not enabled, +// so not defined to catch errors #endif STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf); @@ -123,10 +126,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); @@ -186,7 +189,7 @@ STATIC mp_obj_t array_make_new(const mp_obj_type_t *type_in, size_t n_args, cons #if MICROPY_PY_BUILTINS_BYTEARRAY STATIC mp_obj_t bytearray_make_new(const mp_obj_type_t *type_in, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { (void)type_in; - mp_arg_check_num(n_args, kw_args, 0, 1, false); + mp_arg_check_num(n_args, kw_args, 0, 3, false); if (n_args == 0) { // no args: construct an empty bytearray @@ -210,7 +213,7 @@ mp_obj_t mp_obj_new_memoryview(byte typecode, size_t nitems, void *items) { mp_obj_array_t *self = m_new_obj(mp_obj_array_t); self->base.type = &mp_type_memoryview; self->typecode = typecode; - self->free = 0; + self->memview_offset = 0; self->len = nitems; self->items = items; return MP_OBJ_FROM_PTR(self); @@ -238,14 +241,37 @@ STATIC mp_obj_t memoryview_make_new(const mp_obj_type_t *type_in, size_t n_args, return MP_OBJ_FROM_PTR(self); } + +#if MICROPY_CPYTHON_COMPAT +STATIC mp_obj_t memoryview_cast(const mp_obj_t self_in, const mp_obj_t typecode_in) { + mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in); + const char *typecode = mp_obj_str_get_str(typecode_in); + size_t element_size = mp_binary_get_size('@', typecode[0], NULL); + size_t bytelen = self->len * mp_binary_get_size('@', self->typecode & ~MP_OBJ_ARRAY_TYPECODE_FLAG_RW, NULL); + if (bytelen % element_size != 0) { + mp_raise_TypeError(translate("memoryview: length is not a multiple of itemsize")); + } + mp_obj_array_t *result = MP_OBJ_TO_PTR(mp_obj_new_memoryview(*typecode, bytelen / element_size, self->items)); + + // test if the object can be written to + if (self->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW) { + result->typecode |= MP_OBJ_ARRAY_TYPECODE_FLAG_RW; // indicate writable buffer + } + return MP_OBJ_FROM_PTR(result); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(memoryview_cast_obj, memoryview_cast); +#endif #endif 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 } } @@ -264,22 +290,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); } } @@ -299,7 +326,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); } @@ -314,10 +341,10 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs } case MP_BINARY_OP_CONTAINS: { + #if MICROPY_PY_BUILTINS_BYTEARRAY + // Can search string only in bytearray mp_buffer_info_t lhs_bufinfo; mp_buffer_info_t rhs_bufinfo; - - // Can search string only in bytearray if (mp_get_buffer(rhs_in, &rhs_bufinfo, MP_BUFFER_READ)) { if (!MP_OBJ_IS_TYPE(lhs_in, &mp_type_bytearray)) { return mp_const_false; @@ -326,6 +353,7 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs return mp_obj_new_bool( find_subbytes(lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_bufinfo.len, 1) != NULL); } + #endif // Otherwise, can only look for a scalar numeric value in an array if (MP_OBJ_IS_INT(rhs_in) || mp_obj_is_float(rhs_in)) { @@ -397,7 +425,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; @@ -421,12 +449,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; @@ -441,7 +469,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) { @@ -475,7 +503,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)) { @@ -487,7 +515,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)) { @@ -498,7 +526,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->memview_offset * item_sz); } #endif } else if (MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { @@ -515,7 +543,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)) { @@ -525,11 +553,11 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value if (len_adj != 0) { goto compat_error; } - dest_items += o->free * item_sz; + dest_items += o->memview_offset * item_sz; } #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; @@ -540,11 +568,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; @@ -563,20 +591,20 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value } else if (o->base.type == &mp_type_memoryview) { res = m_new_obj(mp_obj_array_t); *res = *o; - res->free += slice.start; + res->memview_offset += slice.start; res->len = slice.stop - slice.start; #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 if (o->base.type == &mp_type_memoryview) { - index += o->free; + index += o->memview_offset; if (value != MP_OBJ_SENTINEL && !(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) { // store to read-only memoryview return MP_OBJ_NULL; @@ -607,7 +635,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->memview_offset * sz; } #else (void)flags; @@ -646,14 +674,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); @@ -671,7 +699,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 @@ -686,11 +714,20 @@ 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 #if MICROPY_PY_BUILTINS_MEMORYVIEW + +#if MICROPY_CPYTHON_COMPAT +STATIC const mp_rom_map_elem_t memoryview_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_cast), MP_ROM_PTR(&memoryview_cast_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(memoryview_locals_dict, memoryview_locals_dict_table); +#endif + const mp_obj_type_t mp_type_memoryview = { { &mp_type_type }, .name = MP_QSTR_memoryview, @@ -700,6 +737,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 }; #endif @@ -763,14 +803,14 @@ 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; o->cur = 0; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (array->base.type == &mp_type_memoryview) { - o->offset = array->free; + o->offset = array->memview_offset; } #endif return MP_OBJ_FROM_PTR(o); diff --git a/py/objarray.h b/py/objarray.h index 7ad5328f0ea0f..062de8b5770fb 100644 --- a/py/objarray.h +++ b/py/objarray.h @@ -32,11 +32,18 @@ // Used only for memoryview types, set in "typecode" to indicate a writable memoryview #define MP_OBJ_ARRAY_TYPECODE_FLAG_RW (0x80) +// This structure is used for all of bytearray, array.array, memoryview +// objects. Note that memoryview has different meaning for some fields, +// see comment at the beginning of objarray.c. typedef struct _mp_obj_array_t { mp_obj_base_t base; size_t typecode : 8; // free is number of unused elements after len used elements // alloc size = len + free + // But for memoryview, 'free' is reused as offset (in elements) into the + // parent object. (Union is not used to not go into a complication of + // union-of-bitfields with different toolchains). See comments in + // objarray.c. size_t free : (8 * sizeof(size_t) - 8); size_t len; // in elements void *items; diff --git a/py/objattrtuple.c b/py/objattrtuple.c index ac9b808a20438..2e75a23af3ed4 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 5bf25567f09eb..995e0587359b4 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -89,26 +89,22 @@ STATIC void bound_meth_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // not load attribute return; } - if (attr == MP_QSTR___name__) { - mp_obj_bound_meth_t *o = MP_OBJ_TO_PTR(self_in); - dest[0] = MP_OBJ_NEW_QSTR(mp_obj_fun_get_name(o->meth)); - } else if (attr == MP_QSTR___func__) { - mp_obj_bound_meth_t *o = MP_OBJ_TO_PTR(self_in); - dest[0] = o->meth; - } + // Delegate the load to the method object + mp_obj_bound_meth_t *self = MP_OBJ_TO_PTR(self_in); + mp_load_method_maybe(self->meth, attr, dest); } #endif 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 25fe5232a1d8a..2e15e6825aedf 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 6f6772ff1c7ad..e4e3b87bbbb11 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 43e0690d384cb..5e80826c69d97 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 b2785b5b60f98..d9d8c0415d078 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 098aec5d2f22a..4394af9edbfa2 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 } } @@ -164,7 +167,7 @@ STATIC mp_obj_t dict_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_ } } -// TODO: Make sure this is inlined in dict_subscr() below. +// Note: Make sure this is inlined in load part of dict_subscr() below. mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index) { mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *elem = mp_map_lookup(&self->map, index, MP_MAP_LOOKUP); @@ -231,6 +234,7 @@ STATIC mp_obj_t dict_copy(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); +#if MICROPY_PY_BUILTINS_DICT_FROMKEYS // this is a classmethod STATIC mp_obj_t dict_fromkeys(size_t n_args, const mp_obj_t *args) { mp_obj_t iter = mp_getiter(args[1], NULL); @@ -260,6 +264,7 @@ STATIC mp_obj_t dict_fromkeys(size_t n_args, const mp_obj_t *args) { } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_fromkeys_fun_obj, 2, 3, dict_fromkeys); STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(dict_fromkeys_obj, MP_ROM_PTR(&dict_fromkeys_fun_obj)); +#endif STATIC mp_obj_t dict_get_helper(size_t n_args, const mp_obj_t *args, mp_map_lookup_kind_t lookup_kind) { mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); @@ -340,7 +345,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 +441,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 +523,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; @@ -532,7 +537,9 @@ STATIC mp_obj_t dict_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { STATIC const mp_rom_map_elem_t dict_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&dict_clear_obj) }, { MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&dict_copy_obj) }, + #if MICROPY_PY_BUILTINS_DICT_FROMKEYS { MP_ROM_QSTR(MP_QSTR_fromkeys), MP_ROM_PTR(&dict_fromkeys_obj) }, + #endif { MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&dict_get_obj) }, { MP_ROM_QSTR(MP_QSTR_items), MP_ROM_PTR(&dict_items_obj) }, { MP_ROM_QSTR(MP_QSTR_keys), MP_ROM_PTR(&dict_keys_obj) }, @@ -557,7 +564,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 +578,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 @@ -604,9 +611,3 @@ mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key) { dict_get_helper(2, args, MP_MAP_LOOKUP_REMOVE_IF_FOUND); return self_in; } - -mp_map_t *mp_obj_dict_get_map(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); - mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); - return &self->map; -} diff --git a/py/objenumerate.c b/py/objenumerate.c index dee7fc760d600..2c2131ad4f801 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 afefee2caff66..2ea1dc7c79890 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -43,13 +43,24 @@ // Number of items per traceback entry (file, line, block) #define TRACEBACK_ENTRY_LEN (3) -// Number of traceback entries to reserve in the emergency exception buffer -#define EMG_TRACEBACK_ALLOC (2 * TRACEBACK_ENTRY_LEN) - -// Optionally allocated buffer for storing the first argument of an exception -// allocated when the heap is locked. +// Optionally allocated buffer for storing some traceback, the tuple argument, +// and possible string object and data, for when the heap is locked. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF -# if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0 + +// When used the layout of the emergency exception buffer is: +// - traceback entry (file, line, block) +// - traceback entry (file, line, block) +// - mp_obj_tuple_t object +// - n_args * mp_obj_t for tuple +// - mp_obj_str_t object +// - string data +#define EMG_BUF_TRACEBACK_OFFSET (0) +#define EMG_BUF_TRACEBACK_SIZE (2 * TRACEBACK_ENTRY_LEN * sizeof(size_t)) +#define EMG_BUF_TUPLE_OFFSET (EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) +#define EMG_BUF_TUPLE_SIZE(n_args) (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) +#define EMG_BUF_STR_OFFSET (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1)) + +#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 +105,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 +163,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); @@ -162,15 +173,15 @@ mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, con // reserved room (after the traceback data) for a tuple with 1 element. // 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)); + EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) { + o_tuple = (mp_obj_tuple_t *) + ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET); } #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 +246,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 +270,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 +313,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) @@ -414,13 +425,12 @@ mp_obj_t mp_obj_new_exception_msg_vlist(const mp_obj_type_t *exc_type, const com // that buffer to store the string object and its data (at least 16 bytes for // 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) { + && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + 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) - + 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 = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + + EMG_BUF_STR_OFFSET); + 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 +500,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) { @@ -510,11 +520,12 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN); if (self->traceback_data == NULL) { #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF - if (mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)) { + if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) { // 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 *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + + EMG_BUF_TRACEBACK_OFFSET); self->traceback_data = tb; - self->traceback_alloc = EMG_TRACEBACK_ALLOC; + self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t); } else { // Can't allocate and no room in emergency buffer return; @@ -530,7 +541,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 +630,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 +673,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 +710,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 c19658427a579..d7b39add87559 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 80f10e816ec25..3bdfa0b757c25 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,29 +163,33 @@ 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) { + if (signbit(val)) { return mp_obj_new_float(-val); } else { 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 +264,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 +333,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,9 +354,18 @@ 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. +// which are large. +// 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; +} #pragma GCC diagnostic pop #endif // MICROPY_PY_BUILTINS_FLOAT diff --git a/py/objfun.c b/py/objfun.c index 933044ef7132c..5e4792a7ddfee 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -112,9 +112,9 @@ STATIC mp_obj_t fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_k mp_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in); // check number of arguments - mp_arg_check_num_kw_array(n_args, n_kw, self->n_args_min, self->n_args_max, self->is_kw); + mp_arg_check_num_sig(n_args, n_kw, self->sig); - if (self->is_kw) { + if (self->sig & 1) { // function allows keywords // we create a map directly from the given args array @@ -149,10 +149,6 @@ qstr mp_obj_code_get_name(const byte *code_info) { #endif } -#if MICROPY_EMIT_NATIVE -STATIC const mp_obj_type_t mp_type_fun_native; -#endif - qstr mp_obj_fun_get_name(mp_const_obj_t fun_in) { const mp_obj_fun_bc_t *fun = MP_OBJ_TO_PTR(fun_in); #if MICROPY_EMIT_NATIVE @@ -197,20 +193,15 @@ STATIC void dump_args(const mp_obj_t *a, size_t sz) { // than this will try to use the heap, with fallback to stack allocation. #define VM_MAX_STATE_ON_STACK (11 * sizeof(mp_uint_t)) -// Set this to 1 to enable a simple stack overflow check. -#define VM_DETECT_STACK_OVERFLOW (0) - #define DECODE_CODESTATE_SIZE(bytecode, n_state_out_var, state_size_out_var) \ { \ /* bytecode prelude: state size and exception stack size */ \ n_state_out_var = mp_decode_uint_value(bytecode); \ size_t n_exc_stack = mp_decode_uint_value(mp_decode_uint_skip(bytecode)); \ \ - n_state_out_var += VM_DETECT_STACK_OVERFLOW; \ - \ /* 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) \ @@ -259,8 +250,8 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size dump_args(args, n_args); DEBUG_printf("Input kw args: "); dump_args(args + n_args, n_kw * 2); + mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); - DEBUG_printf("Func n_def_args: %d\n", self->n_def_args); size_t n_state, state_size; DECODE_CODESTATE_SIZE(self->bytecode, n_state, state_size); @@ -272,9 +263,17 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size #else if (state_size > VM_MAX_STATE_ON_STACK) { code_state = m_new_obj_var_maybe(mp_code_state_t, byte, state_size); + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + if (code_state != NULL) { + memset(code_state->state, 0, state_size); + } + #endif } if (code_state == NULL) { code_state = alloca(sizeof(mp_code_state_t) + state_size); + #if MICROPY_DEBUG_VM_STACK_OVERFLOW + memset(code_state->state, 0, state_size); + #endif state_size = 0; // indicate that we allocated using alloca } #endif @@ -286,31 +285,34 @@ 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 MICROPY_DEBUG_VM_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); + mp_printf(MICROPY_DEBUG_PRINTER, "VM stack underflow: " INT_FMT "\n", code_state->sp - code_state->state); assert(0); } } - // We can't check the case when an exception is returned in state[n_state - 1] + const byte *bytecode_ptr = mp_decode_uint_skip(mp_decode_uint_skip(self->bytecode)); + size_t n_pos_args = bytecode_ptr[1]; + size_t n_kwonly_args = bytecode_ptr[2]; + // We can't check the case when an exception is returned in state[0] // and there are no arguments, because in this case our detection slot may have // been overwritten by the returned exception (which is allowed). - if (!(vm_return_kind == MP_VM_RETURN_EXCEPTION && self->n_pos_args + self->n_kwonly_args == 0)) { + if (!(vm_return_kind == MP_VM_RETURN_EXCEPTION && n_pos_args + n_kwonly_args == 0)) { // Just check to see that we have at least 1 null object left in the state. bool overflow = true; - for (size_t i = 0; i < n_state - self->n_pos_args - self->n_kwonly_args; i++) { + for (size_t i = 0; i < n_state - n_pos_args - n_kwonly_args; ++i) { if (code_state->state[i] == MP_OBJ_NULL) { overflow = false; break; } } if (overflow) { - printf("VM stack overflow state=%p n_state+1=" UINT_FMT "\n", code_state->state, n_state); + mp_printf(MICROPY_DEBUG_PRINTER, "VM stack overflow state=%p n_state+1=" UINT_FMT "\n", code_state->state, n_state); assert(0); } } -#endif + #endif mp_obj_t result; if (vm_return_kind == MP_VM_RETURN_NORMAL) { @@ -319,8 +321,8 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size } else { // must be an exception because normal functions can't yield assert(vm_return_kind == MP_VM_RETURN_EXCEPTION); - // return value is in fastn[0]==state[n_state - 1] - result = code_state->state[n_state - 1]; + // returned exception is in state[0] + result = code_state->state[0]; } #if MICROPY_ENABLE_PYSTACK @@ -340,7 +342,7 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size } #if MICROPY_PY_FUNCTION_ATTRS -STATIC void fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { +void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { if (dest[0] != MP_OBJ_NULL) { // not load attribute return; @@ -354,14 +356,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 - .attr = fun_bc_attr, -#endif + #if MICROPY_PY_FUNCTION_ATTRS + .attr = mp_obj_fun_bc_attr, + #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,11 +400,11 @@ 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); } -STATIC const mp_obj_type_t mp_type_fun_native = { +const mp_obj_type_t mp_type_fun_native = { { &mp_type_type }, .name = MP_QSTR_function, .call = fun_native_call, @@ -410,79 +412,13 @@ 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; } #endif // MICROPY_EMIT_NATIVE -/******************************************************************************/ -/* viper functions */ - -#if MICROPY_EMIT_NATIVE - -typedef struct _mp_obj_fun_viper_t { - mp_obj_base_t base; - size_t n_args; - void *fun_data; // GC must be able to trace this pointer - mp_uint_t type_sig; -} mp_obj_fun_viper_t; - -typedef mp_uint_t (*viper_fun_0_t)(void); -typedef mp_uint_t (*viper_fun_1_t)(mp_uint_t); -typedef mp_uint_t (*viper_fun_2_t)(mp_uint_t, mp_uint_t); -typedef mp_uint_t (*viper_fun_3_t)(mp_uint_t, mp_uint_t, mp_uint_t); -typedef mp_uint_t (*viper_fun_4_t)(mp_uint_t, mp_uint_t, mp_uint_t, mp_uint_t); - -STATIC mp_obj_t fun_viper_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - mp_obj_fun_viper_t *self = self_in; - - mp_arg_check_num_kw_array(n_args, n_kw, self->n_args, self->n_args, false); - - void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data); - - mp_uint_t ret; - if (n_args == 0) { - ret = ((viper_fun_0_t)fun)(); - } else if (n_args == 1) { - ret = ((viper_fun_1_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4)); - } else if (n_args == 2) { - ret = ((viper_fun_2_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4), mp_convert_obj_to_native(args[1], self->type_sig >> 8)); - } else if (n_args == 3) { - ret = ((viper_fun_3_t)fun)(mp_convert_obj_to_native(args[0], self->type_sig >> 4), mp_convert_obj_to_native(args[1], self->type_sig >> 8), mp_convert_obj_to_native(args[2], self->type_sig >> 12)); - } else { - // compiler allows at most 4 arguments - assert(n_args == 4); - ret = ((viper_fun_4_t)fun)( - mp_convert_obj_to_native(args[0], self->type_sig >> 4), - 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); -} - -STATIC const mp_obj_type_t mp_type_fun_viper = { - { &mp_type_type }, - .name = MP_QSTR_function, - .call = fun_viper_call, - .unary_op = mp_generic_unary_op, -}; - -mp_obj_t mp_obj_new_fun_viper(size_t n_args, void *fun_data, mp_uint_t type_sig) { - mp_obj_fun_viper_t *o = m_new_obj(mp_obj_fun_viper_t); - o->base.type = &mp_type_fun_viper; - o->n_args = n_args; - o->fun_data = fun_data; - o->type_sig = type_sig; - return o; -} - -#endif // MICROPY_EMIT_NATIVE - /******************************************************************************/ /* inline assembler functions */ @@ -521,11 +457,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 +505,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/objfun.h b/py/objfun.h index 457c3cf48c0af..ba533fd329bcd 100644 --- a/py/objfun.h +++ b/py/objfun.h @@ -41,4 +41,6 @@ typedef struct _mp_obj_fun_bc_t { mp_obj_t extra_args[]; } mp_obj_fun_bc_t; +void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest); + #endif // MICROPY_INCLUDED_PY_OBJFUN_H diff --git a/py/objgenerator.c b/py/objgenerator.c index 5e651ac269b5a..5336f7f36a1de 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -52,9 +52,53 @@ typedef struct _mp_obj_gen_instance_t { mp_code_state_t code_state; } 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) { +/******************************************************************************/ +// native generator wrapper + +#if MICROPY_EMIT_NATIVE + +STATIC mp_obj_t native_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; + + // Determine start of prelude, and extract n_state from it +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + uintptr_t prelude_offset = ((uintptr_t *)self_fun->bytecode)[0]; +#pragma GCC diagnostic pop + size_t n_state = mp_decode_uint_value(self_fun->bytecode + prelude_offset); + size_t n_exc_stack = 0; + + // Allocate the generator object, with room for local stack and exception stack + mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte, + n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t)); + o->base.type = &mp_type_gen_instance; + + // Parse the input arguments and set up the code state + o->coroutine_generator = self->coroutine_generator; + o->globals = self_fun->globals; + o->code_state.fun_bc = self_fun; + o->code_state.ip = (const byte *)prelude_offset; + mp_setup_code_state(&o->code_state, n_args, n_kw, args); + + // Indicate we are a native function, which doesn't use this variable + o->code_state.exc_sp = NULL; + + // Prepare the generator instance for execution +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" + uintptr_t start_offset = ((uintptr_t *)self_fun->bytecode)[1]; +#pragma GCC diagnostic pop + o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void *)(self_fun->bytecode + start_offset)); + + return MP_OBJ_FROM_PTR(o); +} + +#endif // MICROPY_EMIT_NATIVE + +STATIC mp_obj_t bc_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; assert(self_fun->base.type == &mp_type_fun_bc); // bytecode prelude: get state size and exception stack size @@ -74,13 +118,37 @@ STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, cons return MP_OBJ_FROM_PTR(o); } +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); + + #if MICROPY_EMIT_NATIVE + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; + if (self_fun->base.type == &mp_type_fun_native) { + return native_gen_wrap_call(self, n_args, n_kw, args); + } + #endif + return bc_gen_wrap_call(self, n_args, n_kw, args); +} + +#if MICROPY_PY_FUNCTION_ATTRS +static void gen_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + 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_attr(self_fun, attr, dest); +} +#endif + const mp_obj_type_t mp_type_gen_wrap = { { &mp_type_type }, .name = MP_QSTR_generator, .call = gen_wrap_call, .unary_op = mp_generic_unary_op, + #if MICROPY_PY_FUNCTION_ATTRS + .attr = gen_attr, + #endif }; + mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun, bool is_coroutine) { mp_obj_gen_wrap_t *o = m_new_obj(mp_obj_gen_wrap_t); o->base.type = &mp_type_gen_wrap; @@ -95,12 +163,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); } @@ -140,7 +208,22 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ self->code_state.old_globals = mp_globals_get(); mp_globals_set(self->globals); self->globals = NULL; - mp_vm_return_kind_t ret_kind = mp_execute_bytecode(&self->code_state, throw_value); + + mp_vm_return_kind_t ret_kind; + + #if MICROPY_EMIT_NATIVE + if (self->code_state.exc_sp == NULL) { + // A native generator, with entry point 2 words into the "bytecode" pointer + typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t); + mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void *)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t))); + ret_kind = fun((void *)&self->code_state, throw_value); + } else + #endif + { + // A bytecode generator + ret_kind = mp_execute_bytecode(&self->code_state, throw_value); + } + self->globals = mp_globals_get(); mp_globals_set(self->code_state.old_globals); @@ -150,8 +233,6 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ // Explicitly mark generator as completed. If we don't do this, // subsequent next() may re-execute statements after last yield // again and again, leading to side effects. - // TODO: check how return with value behaves under such conditions - // in CPython. self->code_state.ip = 0; *ret_val = *self->code_state.sp; break; @@ -164,9 +245,12 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ break; case MP_VM_RETURN_EXCEPTION: { - size_t n_state = mp_decode_uint_value(self->code_state.fun_bc->bytecode); self->code_state.ip = 0; - *ret_val = self->code_state.state[n_state - 1]; + *ret_val = self->code_state.state[0]; + // PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(*ret_val)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + *ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, translate("generator raised StopIteration")); + } break; } } @@ -190,27 +274,18 @@ STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_o return ret; case MP_VM_RETURN_EXCEPTION: - // TODO: Optimization of returning MP_OBJ_STOP_ITERATION is really part - // of mp_iternext() protocol, but this function is called by other methods - // too, which may not handled MP_OBJ_STOP_ITERATION. - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { - mp_obj_t val = mp_obj_exception_get_value(ret); - if (val == mp_const_none) { - return MP_OBJ_STOP_ITERATION; - } - } nlr_raise(ret); } } 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 +303,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, @@ -260,11 +335,10 @@ STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) { case MP_VM_RETURN_YIELD: mp_raise_RuntimeError(translate("generator ignored GeneratorExit")); - // Swallow StopIteration & GeneratorExit (== successful close), and re-raise any other + // Swallow GeneratorExit (== successful close), and re-raise any other case MP_VM_RETURN_EXCEPTION: // ret should always be an instance of an exception class - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit)) || - mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(ret)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { return mp_const_none; } nlr_raise(ret); @@ -309,5 +383,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 44e8fe889480d..26ff9ad1d00e0 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 5a33ccbc04a1b..ac9eb70591bf1 100644 --- a/py/objint.c +++ b/py/objint.c @@ -59,19 +59,17 @@ 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])); + return mp_unary_op(MP_UNARY_OP_INT, args[0]); } case 2: default: { // should be a string, parse it - // TODO proper error checking of argument types size_t l; const char *s = mp_obj_str_get_data(args[0], &l); return mp_parse_num_integer(s, l, mp_obj_get_int(args[1]), NULL); @@ -90,26 +88,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 +122,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 +220,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 +300,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 +319,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 +459,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 +467,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 +484,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 +529,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 +555,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 +571,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 68997ced272fe..9595c1b3a713f 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 0a65098c785a2..63e3464a1a20a 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_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_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_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 d32fdfbe8d32e..3d8de47985781 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 51ec920be15a8..d8b0870e5782f 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; } @@ -270,25 +274,29 @@ STATIC mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in) { return mp_const_none; // return None, as per CPython } -STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_TYPE(args[0], &mp_type_list)); - mp_obj_list_t *self = mp_instance_cast_to_native_base(args[0], &mp_type_list); +inline mp_obj_t mp_obj_list_pop(mp_obj_list_t *self, size_t index) { if (self->len == 0) { mp_raise_IndexError_varg(translate("pop from empty %q"), MP_QSTR_list); } - size_t index = mp_get_index(self->base.type, self->len, n_args == 1 ? MP_OBJ_NEW_SMALL_INT(-1) : args[1], false); mp_obj_t ret = self->items[index]; self->len -= 1; memmove(self->items + index, self->items + index + 1, (self->len - index) * sizeof(mp_obj_t)); // 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; } +STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args) { + mp_check_self(MP_OBJ_IS_TYPE(args[0], &mp_type_list)); + mp_obj_list_t *self = mp_instance_cast_to_native_base(args[0], &mp_type_list); + size_t index = mp_get_index(self->base.type, self->len, n_args == 1 ? MP_OBJ_NEW_SMALL_INT(-1) : args[1], false); + return mp_obj_list_pop(self, index); +} + STATIC void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn, mp_obj_t binop_less_result) { MP_STACK_CHECK(); while (head < tail) { @@ -296,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; @@ -329,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; @@ -371,28 +383,30 @@ STATIC mp_obj_t list_index(size_t n_args, const mp_obj_t *args) { return mp_seq_index_obj(self->items, self->len, n_args, args); } +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[index] = obj; +} + STATIC mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) { mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); mp_obj_list_t *self = mp_instance_cast_to_native_base(self_in, &mp_type_list); // 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; - } - - mp_obj_list_append(self_in, mp_const_none); - - for (mp_int_t i = self->len-1; i > index; i--) { - self->items[i] = self->items[i-1]; + index = self->len; } - self->items[index] = obj; - + mp_obj_list_insert(self, index, obj); return mp_const_none; } @@ -410,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; @@ -456,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) { @@ -526,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/objlist.h b/py/objlist.h index f02030557ba13..eb005e81cf60b 100644 --- a/py/objlist.h +++ b/py/objlist.h @@ -36,5 +36,7 @@ typedef struct _mp_obj_list_t { } mp_obj_list_t; void mp_obj_list_init(mp_obj_list_t *o, size_t n); +mp_obj_t mp_obj_list_pop(mp_obj_list_t *self, size_t index); +void mp_obj_list_insert(mp_obj_list_t *self, size_t index, mp_obj_t obj); #endif // MICROPY_INCLUDED_PY_OBJLIST_H diff --git a/py/objmodule.c b/py/objmodule.c index 90796c5357deb..efe4650157f9d 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); } @@ -64,6 +64,13 @@ STATIC void module_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { mp_map_elem_t *elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP); if (elem != NULL) { dest[0] = elem->value; + #if MICROPY_MODULE_GETATTR + } else if (attr != MP_QSTR___getattr__) { + elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___getattr__), MP_MAP_LOOKUP); + if (elem != NULL) { + dest[0] = mp_call_function_1(elem->value, MP_OBJ_NEW_QSTR(attr)); + } + #endif } } else { // delete/store attribute @@ -153,123 +160,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 +286,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 +309,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 8b595da571606..d1ca17c50274a 100644 --- a/py/objnamedtuple.c +++ b/py/objnamedtuple.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * SPDX-FileCopyrightText: Copyright (c) 2014 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -46,15 +46,21 @@ size_t mp_obj_namedtuple_find_field(const mp_obj_namedtuple_type_t *type, qstr n return (size_t)-1; } -#if MICROPY_PY_COLLECTIONS_ORDEREDDICT +#if MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT 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 mp_obj_dict_t *dictObj = MP_OBJ_TO_PTR(dict); + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + // make it an OrderedDict dictObj->base.type = &mp_type_ordereddict; dictObj->map.is_ordered = 1; + #else + dictObj->base.type = &mp_type_dict; + dictObj->map.is_ordered = 0; + #endif + for (size_t i = 0; i < self->tuple.len; ++i) { mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(fields[i]), self->tuple.items[i]); } @@ -67,7 +73,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 +88,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 +101,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 +109,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 +135,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 8983cd9ad3978..b3a6a171a0220 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 e909533c455b2..f249d79a1d95e 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 7af9f37a11596..fcc0ede98bd60 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 c5d54aede5c32..6089f918141ab 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 40d4d3c7609ab..9bccde76dbe8f 100644 --- a/py/objslice.c +++ b/py/objslice.c @@ -38,8 +38,6 @@ #if MICROPY_PY_BUILTINS_SLICE -// TODO: This implements only variant of slice with 2 integer args only. -// CPython supports 3rd arg (step), plus args can be arbitrary Python objects. typedef struct _mp_obj_slice_t { mp_obj_base_t base; mp_obj_t start; @@ -125,22 +123,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 +217,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 1a59aeaecd31c..a1c611e3813a3 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -37,7 +37,9 @@ #include "supervisor/shared/translate.h" +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict); +#endif STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf); STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in); @@ -140,11 +142,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 +177,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 +300,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; @@ -317,6 +319,7 @@ const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { // check for modulo if (op == MP_BINARY_OP_MODULO) { + #if MICROPY_PY_BUILTINS_STR_OP_MODULO mp_obj_t *args = &rhs_in; size_t n_args = 1; mp_obj_t dict = MP_OBJ_NULL; @@ -327,6 +330,9 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i dict = rhs_in; } return str_modulo_format(lhs_in, n_args, args, dict); + #else + return MP_OBJ_NULL; + #endif } // from now on we need lhs type and data, so extract them @@ -407,7 +413,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 +429,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 +438,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 +450,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 +458,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 +506,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 +541,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 +875,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,20 +947,22 @@ 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 ; } +#if MICROPY_PY_BUILTINS_STR_OP_MODULO 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; } +#endif #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE STATIC NORETURN void terse_str_format_value_error(void) { @@ -972,9 +986,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 +1025,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 +1062,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 +1082,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 +1096,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 +1112,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 +1205,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 +1226,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 +1259,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 +1297,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 +1345,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 +1363,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 +1381,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 +1405,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,11 +1423,12 @@ 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); - return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); + 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_obj_get_type(args[0]), &vstr); } MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format); +#if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) { mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern)); @@ -1443,14 +1464,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 +1480,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 +1506,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 +1520,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 +1565,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ 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 +1574,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ 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 +1584,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ 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 +1614,11 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ 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 } } @@ -1603,6 +1629,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr); } +#endif // The implementation is optimized, returning the original string if there's // nothing to replace. @@ -1699,7 +1726,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 { @@ -1712,6 +1739,7 @@ STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) { } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace); +#if MICROPY_PY_BUILTINS_STR_COUNT STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); @@ -1752,6 +1780,7 @@ STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { return MP_OBJ_NEW_SMALL_INT(num_occurrences); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count); +#endif #if MICROPY_PY_BUILTINS_STR_PARTITION STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) { @@ -1812,7 +1841,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 +1949,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 +1963,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 +1973,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) }, @@ -1962,7 +1991,9 @@ STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) }, { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) }, { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) }, + #if MICROPY_PY_BUILTINS_STR_COUNT { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) }, + #endif #if MICROPY_PY_BUILTINS_STR_PARTITION { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) }, { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) }, @@ -1993,7 +2024,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 +2038,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 +2064,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 +2095,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 +2162,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 +2177,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 +2189,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 +2199,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 +2210,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 +2231,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 +2241,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 +2264,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 cddc6a83a1208..e1698ca5924dd 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 eb40e515437ae..793ec84f31947 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); @@ -196,22 +196,18 @@ STATIC mp_obj_t stringio_make_new(const mp_obj_type_t *type_in, size_t n_args, c mp_obj_stringio_t *o = stringio_new(type_in); if (n_args > 0) { - if (MP_OBJ_IS_INT(args[0])) { - sz = mp_obj_get_int(args[0]); - } else { - mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); - - if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { - o->vstr = m_new_obj(vstr_t); - vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); - o->vstr->len = bufinfo.len; - o->ref_obj = args[0]; - return MP_OBJ_FROM_PTR(o); - } - - sz = bufinfo.len; - initdata = true; + mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); + + if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { + o->vstr = m_new_obj(vstr_t); + vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); + o->vstr->len = bufinfo.len; + o->ref_obj = args[0]; + return MP_OBJ_FROM_PTR(o); } + + sz = bufinfo.len; + initdata = true; } o->vstr = vstr_new(sz); @@ -262,7 +258,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 +270,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 50250abfa9036..d77bbeebcd61f 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) }, @@ -265,7 +264,9 @@ STATIC const mp_rom_map_elem_t struni_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) }, { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) }, { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) }, + #if MICROPY_PY_BUILTINS_STR_COUNT { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) }, + #endif #if MICROPY_PY_BUILTINS_STR_PARTITION { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) }, { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) }, @@ -294,7 +295,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 +314,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 +324,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 d34a7f7624bea..fea4728230a77 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 d2e87e9949b99..7bfb447fa4c58 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 1254b015c9701..1f9bc386adec1 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,15 @@ 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 - printf("mp_obj_class_lookup: Returning: "); - 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 + #if DEBUG_PRINT + DEBUG_printf("mp_obj_class_lookup: Returning: "); + mp_obj_print_helper(MICROPY_DEBUG_PRINTER, lookup->dest[0], PRINT_REPR); + if (lookup->dest[1] != MP_OBJ_NULL) { + // Don't try to repr() lookup->dest[1], as we can be called recursively + DEBUG_printf(" <%s @%p>", mp_obj_get_type_str(lookup->dest[1]), MP_OBJ_TO_PTR(lookup->dest[1])); + } + DEBUG_printf("\n"); + #endif return; } } @@ -215,13 +218,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 +237,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 +377,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 } @@ -398,6 +401,7 @@ const byte mp_unary_op_method_name[MP_UNARY_OP_NUM_RUNTIME] = { [MP_UNARY_OP_BOOL] = MP_QSTR___bool__, [MP_UNARY_OP_LEN] = MP_QSTR___len__, [MP_UNARY_OP_HASH] = MP_QSTR___hash__, + [MP_UNARY_OP_INT] = MP_QSTR___int__, #if MICROPY_PY_ALL_SPECIAL_METHODS [MP_UNARY_OP_POSITIVE] = MP_QSTR___pos__, [MP_UNARY_OP_NEGATIVE] = MP_QSTR___neg__, @@ -443,9 +447,21 @@ STATIC mp_obj_t instance_unary_op(mp_unary_op_t op, mp_obj_t self_in) { return mp_unary_op(op, self->subobj[0]); } else if (member[0] != MP_OBJ_NULL) { mp_obj_t val = mp_call_function_1(member[0], self_in); - // __hash__ must return a small int - if (op == MP_UNARY_OP_HASH) { - val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + + switch (op) { + case MP_UNARY_OP_HASH: + // __hash__ must return a small int + val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + break; + case MP_UNARY_OP_INT: + // Must return int + if (!MP_OBJ_IS_INT(val)) { + mp_raise_TypeError(NULL); + } + break; + default: + // No need to do anything + ; } return val; } else { @@ -482,8 +498,7 @@ const byte mp_binary_op_method_name[MP_BINARY_OP_NUM_RUNTIME] = { // MP_BINARY_OP_NOT_EQUAL, // a != b calls a == b and inverts result [MP_BINARY_OP_CONTAINS] = MP_QSTR___contains__, - // All inplace methods are optional, and normal methods will be used - // as a fallback. + // If an inplace method is not found a normal method will be used as a fallback [MP_BINARY_OP_INPLACE_ADD] = MP_QSTR___iadd__, [MP_BINARY_OP_INPLACE_SUBTRACT] = MP_QSTR___isub__, #if MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS @@ -596,7 +611,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 +626,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, @@ -678,7 +693,6 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des mp_load_method_maybe(self_in, MP_QSTR___getattr__, dest2); if (dest2[0] != MP_OBJ_NULL) { // __getattr__ exists, call it and return its result - // XXX if this fails to load the requested attr, should we catch the attribute error and return silently? dest2[2] = MP_OBJ_NEW_QSTR(attr); dest[0] = mp_call_method_n_kw(1, 0, dest2); return; @@ -821,41 +835,32 @@ STATIC void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { STATIC mp_obj_t instance_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in); - mp_obj_t member[2] = {MP_OBJ_NULL}; + mp_obj_t member[4] = {MP_OBJ_NULL, MP_OBJ_NULL, index, value}; struct class_lookup_data lookup = { .obj = self, .meth_offset = offsetof(mp_obj_type_t, subscr), .dest = member, .is_type = false, }; - size_t meth_args; if (value == MP_OBJ_NULL) { // delete item lookup.attr = MP_QSTR___delitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 2; } else if (value == MP_OBJ_SENTINEL) { // load item lookup.attr = MP_QSTR___getitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 2; } else { // store item lookup.attr = MP_QSTR___setitem__; - mp_obj_class_lookup(&lookup, self->base.type); - meth_args = 3; } - if (member[0] == MP_OBJ_SENTINEL) { // native base subscr exists - mp_obj_type_t *subobj_type = mp_obj_get_type(self->subobj[0]); - // return mp_obj_subscr(self->subobj[0], index, value, instance); - mp_obj_t ret = subobj_type->subscr(self_in, index, value); + mp_obj_class_lookup(&lookup, self->base.type); + if (member[0] == MP_OBJ_SENTINEL) { + mp_obj_t ret = mp_obj_subscr(self->subobj[0], index, value); // May have called port specific C code. Make sure it didn't mess up the heap. assert_heap_ok(); return ret; } else if (member[0] != MP_OBJ_NULL) { - mp_obj_t args[3] = {self_in, index, value}; - // TODO probably need to call mp_convert_member_lookup, and use mp_call_method_n_kw - mp_obj_t ret = mp_call_function_n_kw(member[0], meth_args, 0, args); + size_t n_args = value == MP_OBJ_NULL || value == MP_OBJ_SENTINEL ? 1 : 2; + mp_obj_t ret = mp_call_method_n_kw(n_args, 0, member); if (value == MP_OBJ_SENTINEL) { return ret; } else { @@ -889,10 +894,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 +1030,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 +1058,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, @@ -1063,8 +1068,6 @@ STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } else { // delete/store attribute - // TODO CPython allows STORE_ATTR to a class, but is this the correct implementation? - if (self->locals_dict != NULL) { assert(self->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now mp_map_t *locals_map = &self->locals_dict->map; @@ -1135,10 +1138,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 +1164,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 +1172,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 +1198,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 +1242,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 +1279,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 +1290,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 +1376,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 +1443,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 +1456,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 28621cf89845f..c8a975e0d2e56 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 946b41eac38b1..1e6a5888eb36c 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 a72829b203905..ec27d04e4343b 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 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m 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,25 @@ 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 +// EXACT_POWER_OF_10 is the largest value of x so that 10^x can be stored exactly in a float +// Note: EXACT_POWER_OF_10 is at least floor(log_5(2^mantissa_length)). Indeed, 10^n = 2^n * 5^n +// so we only have to store the 5^n part in the mantissa (the 2^n part will go into the float's +// exponent). + #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 +#define EXACT_POWER_OF_10 (9) + #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 +#define EXACT_POWER_OF_10 (22) + #endif const char *top = str + len; mp_float_t dec_val = 0; @@ -214,7 +220,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; @@ -297,7 +303,17 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool exp_val -= SMALL_NORMAL_EXP; dec_val *= SMALL_NORMAL_VAL; } - dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val); + + // At this point, we need to multiply the mantissa by its base 10 exponent. If possible, + // we would rather manipulate numbers that have an exact representation in IEEE754. It + // turns out small positive powers of 10 do, whereas small negative powers of 10 don't. + // So in that case, we'll yield a division of exact values rather than a multiplication + // of slightly erroneous values. + if (exp_val < 0 && exp_val >= -EXACT_POWER_OF_10) { + dec_val /= MICROPY_FLOAT_C_FUN(pow)(10, -exp_val); + } else { + dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val); + } } // negate value if needed @@ -320,17 +336,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 +354,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 e4ac6d00ed670..0802b435f05ba 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 9b438453adb5d..4e352ce7a4622 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 e4da157f055cb..ad9684f3c5a15 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 fadf1f8822412..2b2439eae1ba3 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/py.mk b/py/py.mk index 3f94aa67a0e54..f61bad1faf229 100644 --- a/py/py.mk +++ b/py/py.mk @@ -79,7 +79,7 @@ endif ifeq ($(MICROPY_PY_BTREE),1) BTREE_DIR = lib/berkeley-db-1.xx -BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ -Dvirt_fd_t=mp_obj_t "-DVIRT_FD_T_HEADER=" $(BTREE_DEFS_EXTRA) +BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ "-Dvirt_fd_t=void*" $(BTREE_DEFS_EXTRA) INC += -I$(TOP)/$(BTREE_DIR)/PORT/include SRC_MOD += extmod/modbtree.c SRC_MOD += $(addprefix $(BTREE_DIR)/,\ @@ -106,9 +106,9 @@ $(BUILD)/extmod/modbtree.o: CFLAGS += $(BTREE_DEFS) endif ifeq ($(CIRCUITPY_ULAB),1) -SRC_MOD += $(patsubst $(TOP)/%,%,$(wildcard $(TOP)/extmod/ulab/code/*.c)) -SRC_MOD += $(patsubst $(TOP)/%,%,$(wildcard $(TOP)/extmod/ulab/code/*/*.c)) -CFLAGS_MOD += -DCIRCUITPY_ULAB=1 -DMODULE_ULAB_ENABLED=1 +ULAB_SRCS := $(shell find $(TOP)/extmod/ulab/code -type f -name "*.c") +SRC_MOD += $(patsubst $(TOP)/%,%,$(ULAB_SRCS)) +CFLAGS_MOD += -DCIRCUITPY_ULAB=1 -DMODULE_ULAB_ENABLED=1 -iquote $(TOP)/extmod/ulab/code $(BUILD)/extmod/ulab/code/%.o: CFLAGS += -Wno-missing-declarations -Wno-missing-prototypes -Wno-unused-parameter -Wno-float-equal -Wno-sign-compare -Wno-cast-align -Wno-shadow -DCIRCUITPY endif @@ -261,12 +261,8 @@ PY_EXTMOD_O_BASENAME = \ extmod/moduhashlib.o \ extmod/modubinascii.o \ extmod/virtpin.o \ - extmod/modussl_axtls.o \ - extmod/modussl_mbedtls.o \ extmod/modurandom.o \ extmod/moduselect.o \ - extmod/modwebsocket.o \ - extmod/modwebrepl.o \ extmod/modframebuf.o \ extmod/vfs.o \ extmod/vfs_reader.o \ @@ -379,7 +375,7 @@ endif # may require disabling tail jump optimization. This will make sure that # each opcode has its own dispatching jump which will improve branch # branch predictor efficiency. -# http://article.gmane.org/gmane.comp.lang.lua.general/75426 +# https://marc.info/?l=lua-l&m=129778596120851 # http://hg.python.org/cpython/file/b127046831e2/Python/ceval.c#l828 # http://www.emulators.com/docs/nx25_nostradamus.htm #-fno-crossjumping diff --git a/py/pystack.c b/py/pystack.c index 0def75b109a05..c48437aa74a41 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 3fbcdeeb8a50a..66ff2a6950ea0 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 c9ba298fb7bd1..a10adc578a137 --- a/py/qstr.c +++ b/py/qstr.c @@ -37,7 +37,6 @@ // NOTE: we are using linear arrays to store and search for qstr's (unique strings, interned strings) // ultimately we will replace this with a static hash table of some kind -// also probably need to include the length in the string data, to allow null bytes in the string #if MICROPY_DEBUG_VERBOSE // print debugging info #define DEBUG_printf DEBUG_printf @@ -46,34 +45,9 @@ #endif // A qstr is an index into the qstr pool. -// The data for a qstr contains (hash, length, data): -// - hash (configurable number of bytes) -// - length (configurable number of bytes) -// - data ("length" number of bytes) -// - \0 terminated (so they can be printed using printf) - -#if MICROPY_QSTR_BYTES_IN_HASH == 1 - #define Q_HASH_MASK (0xff) - #define Q_GET_HASH(q) ((mp_uint_t)(q)[0]) - #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); } while (0) -#elif MICROPY_QSTR_BYTES_IN_HASH == 2 - #define Q_HASH_MASK (0xffff) - #define Q_GET_HASH(q) ((mp_uint_t)(q)[0] | ((mp_uint_t)(q)[1] << 8)) - #define Q_SET_HASH(q, hash) do { (q)[0] = (hash); (q)[1] = (hash) >> 8; } while (0) -#else - #error unimplemented qstr hash decoding -#endif -#define Q_GET_ALLOC(q) (MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + Q_GET_LENGTH(q) + 1) -#define Q_GET_DATA(q) ((q) + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN) -#if MICROPY_QSTR_BYTES_IN_LEN == 1 - #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH]) - #define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); } while (0) -#elif MICROPY_QSTR_BYTES_IN_LEN == 2 - #define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH] | ((q)[MICROPY_QSTR_BYTES_IN_HASH + 1] << 8)) - #define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); (q)[MICROPY_QSTR_BYTES_IN_HASH + 1] = (len) >> 8; } while (0) -#else - #error unimplemented qstr length decoding -#endif +// The data for a qstr is \0 terminated (so they can be printed using printf) + +#define Q_HASH_MASK ((1 << (8 * MICROPY_QSTR_BYTES_IN_HASH)) - 1) #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL #define QSTR_ENTER() mp_thread_mutex_lock(&MP_STATE_VM(qstr_mutex), 1) @@ -83,6 +57,10 @@ #define QSTR_EXIT() #endif +// Initial number of entries for qstr pool, set so that the first dynamically +// allocated pool is twice this size. The value here must be <= MP_QSTRnumber_of. +#define MICROPY_ALLOC_QSTR_ENTRIES_INIT (10) + // this must match the equivalent function in makeqstrdata.py mp_uint_t qstr_compute_hash(const byte *data, size_t len) { // djb2 algorithm; see http://www.cse.yorku.ca/~oz/hash.html @@ -98,19 +76,30 @@ mp_uint_t qstr_compute_hash(const byte *data, size_t len) { return hash; } +const qstr_attr_t mp_qstr_const_attr[] = { + #ifndef NO_QSTR +#define QDEF(id, hash, len, str) { hash, len }, +#define TRANSLATION(id, length, compressed ...) + #include "genhdr/qstrdefs.generated.h" +#undef TRANSLATION +#undef QDEF + #endif +}; + const qstr_pool_t mp_qstr_const_pool = { NULL, // no previous pool 0, // no previous pool - 10, // set so that the first dynamically allocated pool is twice this size; must be <= the len (just below) + MICROPY_ALLOC_QSTR_ENTRIES_INIT, MP_QSTRnumber_of, // corresponds to number of strings in array just below + (qstr_attr_t *)mp_qstr_const_attr, { -#ifndef NO_QSTR -#define QDEF(id, str) str, -#define TRANSLATION(id, length, compressed...) -#include "genhdr/qstrdefs.generated.h" + #ifndef NO_QSTR +#define QDEF(id, hash, len, str) str, +#define TRANSLATION(id, length, compressed ...) + #include "genhdr/qstrdefs.generated.h" #undef TRANSLATION #undef QDEF -#endif + #endif }, }; @@ -122,7 +111,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 @@ -130,20 +119,22 @@ void qstr_init(void) { #endif } -STATIC const byte *find_qstr(qstr q) { +STATIC const char *find_qstr(qstr q, qstr_attr_t *attr) { // search pool for this qstr // total_prev_len==0 in the final pool, so the loop will always terminate qstr_pool_t *pool = MP_STATE_VM(last_pool); while (q < pool->total_prev_len) { pool = pool->prev; } - assert(q - pool->total_prev_len < pool->len); - return pool->qstrs[q - pool->total_prev_len]; + q -= pool->total_prev_len; + assert(q < pool->len); + *attr = pool->attrs[q]; + return pool->qstrs[q]; } // qstr_mutex must be taken while in this function -STATIC qstr qstr_add(const byte *q_ptr) { - DEBUG_printf("QSTR: add hash=%d len=%d data=%.*s\n", Q_GET_HASH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_DATA(q_ptr)); +STATIC qstr qstr_add(mp_uint_t hash, mp_uint_t len, const char *q_ptr) { + DEBUG_printf("QSTR: add hash=%d len=%d data=%.*s\n", hash, len, len, q_ptr); // make sure we have room in the pool for a new qstr if (MP_STATE_VM(last_pool)->len >= MP_STATE_VM(last_pool)->alloc) { @@ -151,11 +142,20 @@ 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); - if (pool == NULL) { + #ifdef MICROPY_QSTR_EXTRA_POOL + // Put a lower bound on the allocation size in case the extra qstr pool has few entries + if (new_pool_length < MICROPY_ALLOC_QSTR_ENTRIES_INIT) { + new_pool_length = MICROPY_ALLOC_QSTR_ENTRIES_INIT; + } + #endif + mp_uint_t pool_size = sizeof(qstr_pool_t) + sizeof(const char *) * new_pool_length; + void *chunk = m_malloc_maybe(pool_size + sizeof(qstr_attr_t) * new_pool_length, true); + if (chunk == NULL) { QSTR_EXIT(); m_malloc_fail(new_pool_length); } + qstr_pool_t *pool = (qstr_pool_t *)chunk; + pool->attrs = (qstr_attr_t *)(void *)((char *)chunk + pool_size); pool->prev = MP_STATE_VM(last_pool); pool->total_prev_len = MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len; pool->alloc = new_pool_length; @@ -165,21 +165,26 @@ STATIC qstr qstr_add(const byte *q_ptr) { } // add the new qstr - MP_STATE_VM(last_pool)->qstrs[MP_STATE_VM(last_pool)->len++] = q_ptr; + mp_uint_t at = MP_STATE_VM(last_pool)->len; + MP_STATE_VM(last_pool)->attrs[at].hash = hash; + MP_STATE_VM(last_pool)->attrs[at].len = len; + MP_STATE_VM(last_pool)->qstrs[at] = q_ptr; + MP_STATE_VM(last_pool)->len++; // return id for the newly-added qstr - return MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len - 1; + return MP_STATE_VM(last_pool)->total_prev_len + at; } 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) { - for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - if (Q_GET_HASH(*q) == str_hash && Q_GET_LENGTH(*q) == str_len && memcmp(Q_GET_DATA(*q), str, str_len) == 0) { - return pool->total_prev_len + (q - pool->qstrs); + qstr_attr_t *attrs = pool->attrs; + for (mp_uint_t at = 0, top = pool->len; at < top; at++) { + if (attrs[at].hash == str_hash && attrs[at].len == str_len && memcmp(pool->qstrs[at], str, str_len) == 0) { + return pool->total_prev_len + at; } } } @@ -200,14 +205,14 @@ qstr qstr_from_strn(const char *str, size_t len) { // qstr does not exist in interned pool so need to add it // compute number of bytes needed to intern this string - size_t n_bytes = MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len + 1; + size_t n_bytes = len + 1; if (MP_STATE_VM(qstr_last_chunk) != NULL && MP_STATE_VM(qstr_last_used) + n_bytes > MP_STATE_VM(qstr_last_alloc)) { // not enough room at end of previously interned string so try to grow - byte *new_p = m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_alloc) + n_bytes, false); + char *new_p = m_renew_maybe(char, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_alloc) + n_bytes, false); if (new_p == NULL) { // could not grow existing memory; shrink it to fit previous - (void)m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_used), false); + (void)m_renew_maybe(char, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_used), false); MP_STATE_VM(qstr_last_chunk) = NULL; } else { // could grow existing memory @@ -221,10 +226,10 @@ qstr qstr_from_strn(const char *str, size_t len) { if (al < MICROPY_ALLOC_QSTR_CHUNK_INIT) { al = MICROPY_ALLOC_QSTR_CHUNK_INIT; } - MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(byte, al); + MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(char, al); if (MP_STATE_VM(qstr_last_chunk) == NULL) { // failed to allocate a large chunk so try with exact size - MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(byte, n_bytes); + MP_STATE_VM(qstr_last_chunk) = m_new_ll_maybe(char, n_bytes); if (MP_STATE_VM(qstr_last_chunk) == NULL) { QSTR_EXIT(); m_malloc_fail(n_bytes); @@ -236,39 +241,41 @@ qstr qstr_from_strn(const char *str, size_t len) { } // allocate memory from the chunk for this new interned string's data - byte *q_ptr = MP_STATE_VM(qstr_last_chunk) + MP_STATE_VM(qstr_last_used); + char *q_ptr = MP_STATE_VM(qstr_last_chunk) + MP_STATE_VM(qstr_last_used); MP_STATE_VM(qstr_last_used) += n_bytes; // store the interned strings' data - 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); - q_ptr[MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len] = '\0'; - q = qstr_add(q_ptr); + mp_uint_t hash = qstr_compute_hash((const byte *)str, len); + memcpy(q_ptr, str, len); + q_ptr[len] = '\0'; + q = qstr_add(hash, len, q_ptr); } QSTR_EXIT(); return q; } mp_uint_t PLACE_IN_ITCM(qstr_hash)(qstr q) { - return Q_GET_HASH(find_qstr(q)); + qstr_attr_t attr; + find_qstr(q, &attr); + return attr.hash; } size_t qstr_len(qstr q) { - const byte *qd = find_qstr(q); - return Q_GET_LENGTH(qd); + qstr_attr_t attr; + find_qstr(q, &attr); + return attr.len; } const char *qstr_str(qstr q) { - const byte *qd = find_qstr(q); - return (const char*)Q_GET_DATA(qd); + qstr_attr_t attr; + return find_qstr(q, &attr); } const byte *qstr_data(qstr q, size_t *len) { - const byte *qd = find_qstr(q); - *len = Q_GET_LENGTH(qd); - return Q_GET_DATA(qd); + qstr_attr_t attr; + const char *qd = find_qstr(q, &attr); + *len = attr.len; + return (byte *)qd; } void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, size_t *n_total_bytes) { @@ -280,13 +287,14 @@ void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, si for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) { *n_pool += 1; *n_qstr += pool->len; - for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - *n_str_data_bytes += Q_GET_ALLOC(*q); + for (const qstr_attr_t *q = pool->attrs, *q_top = pool->attrs + pool->len; q < q_top; q++) { + *n_str_data_bytes += sizeof(*q) + q->len + 1; } #if MICROPY_ENABLE_GC - *n_total_bytes += gc_nbytes(pool); // this counts actual bytes used in heap + // this counts actual bytes used in heap + *n_total_bytes += gc_nbytes(pool) - sizeof(qstr_attr_t) * pool->alloc; #else - *n_total_bytes += sizeof(qstr_pool_t) + sizeof(qstr) * pool->alloc; + *n_total_bytes += sizeof(qstr_pool_t) + sizeof(const char *) * pool->alloc; #endif } *n_total_bytes += *n_str_data_bytes; @@ -297,8 +305,8 @@ void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, si void qstr_dump_data(void) { QSTR_ENTER(); for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) { - for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - mp_printf(&mp_plat_print, "Q(%s)\n", Q_GET_DATA(*q)); + for (const char **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { + mp_printf(&mp_plat_print, "Q(%s)\n", *q); } } QSTR_EXIT(); diff --git a/py/qstr.h b/py/qstr.h index 070a3cd4f8803..288bf5dbac061 100644 --- a/py/qstr.h +++ b/py/qstr.h @@ -37,22 +37,40 @@ // 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 }; typedef size_t qstr; +typedef struct _qstr_attr_t { + #if MICROPY_QSTR_BYTES_IN_HASH == 1 + uint8_t hash; + #elif MICROPY_QSTR_BYTES_IN_HASH == 2 + uint16_t hash; + #else + #error unimplemented qstr hash decoding + #endif + #if MICROPY_QSTR_BYTES_IN_LEN == 1 + uint8_t len; + #elif MICROPY_QSTR_BYTES_IN_LEN == 2 + uint16_t len; + #else + #error unimplemented qstr length decoding + #endif +} qstr_attr_t; + typedef struct _qstr_pool_t { struct _qstr_pool_t *prev; size_t total_prev_len; size_t alloc; size_t len; - const byte *qstrs[]; + qstr_attr_t *attrs; + const char *qstrs[]; } qstr_pool_t; #define QSTR_FROM_STR_STATIC(s) (qstr_from_strn((s), strlen(s))) diff --git a/py/qstrdefs.h b/py/qstrdefs.h index b682671970bdd..6337399d16a9b 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. @@ -37,8 +39,13 @@ Q() Q(*) Q(_) Q(/) +#if MICROPY_PY_BUILTINS_STR_OP_MODULO Q(%#o) Q(%#x) +#else +Q({:#o}) +Q({:#x}) +#endif Q({:#b}) Q( ) Q(\n) diff --git a/py/reader.c b/py/reader.c index 1b0bbf094a57a..dfd5daf63eba0 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 f9f8a590a67d4..9f20004690262 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 3e8928a32c055..8e68ea32538dc 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 785c0fb5386bc..6cc10bb007ad7 100644 --- a/py/repl.c +++ b/py/repl.c @@ -26,6 +26,7 @@ #include #include "py/obj.h" +#include "py/objmodule.h" #include "py/runtime.h" #include "py/builtin.h" #include "py/repl.h" @@ -50,7 +51,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 +62,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 +96,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; } } } @@ -130,6 +144,93 @@ bool mp_repl_continue_with_input(const char *input) { return false; } +STATIC bool test_qstr(mp_obj_t obj, qstr name) { + if (obj) { + // try object member + mp_obj_t dest[2]; + mp_load_method_protected(obj, name, dest, true); + return dest[0] != MP_OBJ_NULL; + } else { + // try builtin module + return mp_map_lookup((mp_map_t *)&mp_builtin_module_map, + MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP); + } +} + +STATIC const char *find_completions(const char *s_start, size_t s_len, + mp_obj_t obj, size_t *match_len, qstr *q_first, qstr *q_last) { + + const char *match_str = NULL; + *match_len = 0; + *q_first = *q_last = 0; + size_t nqstr = QSTR_TOTAL(); + for (qstr q = MP_QSTR_ + 1; q < nqstr; ++q) { + size_t 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) { + if (test_qstr(obj, q)) { + // special case; filter out words that begin with underscore + // unless there's already a partial match + if (s_len == 0 && d_str[0] == '_') { + continue; + } + if (match_str == NULL) { + match_str = d_str; + *match_len = d_len; + } else { + // search for longest common prefix of match_str and d_str + // (assumes these strings are null-terminated) + for (size_t j = s_len; j <= *match_len && j <= d_len; ++j) { + if (match_str[j] != d_str[j]) { + *match_len = j; + break; + } + } + } + if (*q_first == 0) { + *q_first = q; + } + *q_last = q; + } + } + } + return match_str; +} + +STATIC void print_completions(const mp_print_t *print, + const char *s_start, size_t s_len, + mp_obj_t obj, qstr q_first, qstr q_last) { + + #define WORD_SLOT_LEN (16) + #define MAX_LINE_LEN (4 * WORD_SLOT_LEN) + + 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); + if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) { + if (test_qstr(obj, q)) { + int gap = (line_len + WORD_SLOT_LEN - 1) / WORD_SLOT_LEN * WORD_SLOT_LEN - line_len; + if (gap < 2) { + gap += WORD_SLOT_LEN; + } + if (line_len + gap + d_len <= MAX_LINE_LEN) { + // TODO optimise printing of gap? + for (int j = 0; j < gap; ++j) { + mp_print_str(print, " "); + } + mp_print_str(print, d_str); + line_len += gap + d_len; + } else { + mp_printf(print, "\n%s", d_str); + line_len = d_len; + } + } + } + } + mp_print_str(print, "\n"); +} + size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print, const char **compl_str) { // scan backwards to find start of "a.b.c" chain const char *org_str = str; @@ -142,137 +243,82 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print } } - size_t nqstr = QSTR_TOTAL(); - // begin search in outer global dict which is accessed from __main__ mp_obj_t obj = MP_OBJ_FROM_PTR(&mp_module___main__); mp_obj_t dest[2]; + const char *s_start; + size_t s_len; + for (;;) { // get next word in string to complete - const char *s_start = str; + s_start = str; while (str < top && *str != '.') { ++str; } - size_t s_len = str - s_start; - - if (str < top) { - // a complete word, lookup in current object - qstr q = qstr_find_strn(s_start, s_len); - if (q == MP_QSTR_NULL) { - // lookup will fail - return 0; - } - mp_load_method_protected(obj, q, dest, true); - obj = dest[0]; // attribute, method, or MP_OBJ_NULL if nothing found - - if (obj == MP_OBJ_NULL) { - // lookup failed - return 0; - } + s_len = str - s_start; - // skip '.' to move to next word - ++str; - - } else { + if (str == top) { // end of string, do completion on this partial name + break; + } - // look for matches - const char *match_str = NULL; - size_t match_len = 0; - 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); - 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) { - // special case; filter out words that begin with underscore - // unless there's already a partial match - if (s_len == 0 && d_str[0] == '_') { - continue; - } - if (match_str == NULL) { - match_str = d_str; - match_len = d_len; - } else { - // search for longest common prefix of match_str and d_str - // (assumes these strings are null-terminated) - for (size_t j = s_len; j <= match_len && j <= d_len; ++j) { - if (match_str[j] != d_str[j]) { - match_len = j; - break; - } - } - } - if (q_first == 0) { - q_first = q; - } - q_last = q; - } - } - } + // a complete word, lookup in current object + qstr q = qstr_find_strn(s_start, s_len); + if (q == MP_QSTR_NULL) { + // lookup will fail + return 0; + } + mp_load_method_protected(obj, q, dest, true); + obj = dest[0]; // attribute, method, or MP_OBJ_NULL if nothing found - // nothing found - if (q_first == 0) { - if (s_len == 0) { - *compl_str = " "; - return 4; - } - // If there're no better alternatives, and if it's first word - // in the line, try to complete "import". - if (s_start == org_str) { - static const char import_str[] = "import "; - if (memcmp(s_start, import_str, s_len) == 0) { - *compl_str = import_str + s_len; - return sizeof(import_str) - 1 - s_len; - } - } + if (obj == MP_OBJ_NULL) { + // lookup failed + return 0; + } - return 0; - } + // skip '.' to move to next word + ++str; + } - // 1 match found, or multiple matches with a common prefix - if (q_first == q_last || match_len > s_len) { - *compl_str = match_str + s_len; - return match_len - s_len; - } + // after "import", suggest built-in modules + static const char import_str[] = "import "; + if (len >= 7 && !memcmp(org_str, import_str, 7)) { + obj = MP_OBJ_NULL; + } - // multiple matches found, print them out - - #define WORD_SLOT_LEN (16) - #define MAX_LINE_LEN (4 * WORD_SLOT_LEN) - - 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); - 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) { - int gap = (line_len + WORD_SLOT_LEN - 1) / WORD_SLOT_LEN * WORD_SLOT_LEN - line_len; - if (gap < 2) { - gap += WORD_SLOT_LEN; - } - if (line_len + gap + d_len <= MAX_LINE_LEN) { - // TODO optimise printing of gap? - for (int j = 0; j < gap; ++j) { - mp_print_str(print, " "); - } - mp_print_str(print, d_str); - line_len += gap + d_len; - } else { - mp_printf(print, "\n%s", d_str); - line_len = d_len; - } - } - } - } - mp_print_str(print, "\n"); + // look for matches + size_t match_len; + qstr q_first, q_last; + const char *match_str = + find_completions(s_start, s_len, obj, &match_len, &q_first, &q_last); - return (size_t)(-1); // indicate many matches + // nothing found + if (q_first == 0) { + // If there're no better alternatives, and if it's first word + // in the line, try to complete "import". + if (s_start == org_str && s_len > 0) { + if (memcmp(s_start, import_str, s_len) == 0) { + *compl_str = import_str + s_len; + return sizeof(import_str) - 1 - s_len; + } + } + if (q_first == 0) { + *compl_str = " "; + return s_len ? 0 : 4; } } + + // 1 match found, or multiple matches with a common prefix + if (q_first == q_last || match_len > s_len) { + *compl_str = match_str + s_len; + return match_len - s_len; + } + + // multiple matches found, print them out + print_completions(print, s_start, s_len, obj, q_first, q_last); + + return (size_t)(-1); // indicate many matches } #endif // MICROPY_HELPER_REPL diff --git a/py/ringbuf.c b/py/ringbuf.c index c19f1d44bc74d..f4be5ca3fb0cf 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 476bd428f99ce..88d88d86e91e0 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 a3acb954a6014..72eb2fa4c5f89 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,15 @@ 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_THREAD_GIL_EXIT(); + + // 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_DEINIT_FUNC MICROPY_PORT_DEINIT_FUNC; -#endif + #endif } mp_obj_t mp_load_name(qstr qst) { @@ -175,13 +177,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 } } @@ -238,6 +240,7 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { case MP_UNARY_OP_HASH: return arg; case MP_UNARY_OP_POSITIVE: + case MP_UNARY_OP_INT: return arg; case MP_UNARY_OP_NEGATIVE: // check for overflow @@ -275,13 +278,22 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { return result; } } - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - 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)); - #endif + // With MP_UNARY_OP_INT, mp_unary_op() becomes a fallback for mp_obj_get_int(). + // In this case provide a more focused error message to not confuse, e.g. chr(1.0) + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { + if (op == MP_UNARY_OP_INT) { + mp_raise_TypeError(translate("can't convert to int")); + } else { + mp_raise_TypeError(translate("unsupported type for operator")); + } + } else { + if (op == MP_UNARY_OP_INT) { + mp_raise_TypeError_varg(translate("can't convert %q to int"), mp_obj_get_type_qstr(arg)); + } else { + mp_raise_TypeError_varg(translate("unsupported type for %q: '%q'"), + mp_unary_op_method_name[op], mp_obj_get_type_qstr(arg)); + } + } } } @@ -359,11 +371,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 +413,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,21 +520,25 @@ 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; } - // TODO: We just should make mp_obj_new_int() inline and use that + // This is an inlined version of mp_obj_new_int, for speed if (MP_SMALL_INT_FITS(lhs_val)) { return MP_OBJ_NEW_SMALL_INT(lhs_val); } else { - return mp_obj_new_int(lhs_val); + return mp_obj_new_int_from_ll(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 +546,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 +554,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 +578,7 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r } } -#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 +591,7 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r // 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 +609,11 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r 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 +651,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 +879,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 +943,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 +1015,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 +1023,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 +1051,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 +1067,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 +1087,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 +1121,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 +1149,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 +1199,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 +1240,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 +1262,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 +1290,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 +1298,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 } } @@ -1308,15 +1334,8 @@ mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t th if (send_value == mp_const_none) { mp_load_method_maybe(self_in, MP_QSTR___next__, dest); if (dest[0] != MP_OBJ_NULL) { - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - *ret_val = mp_call_method_n_kw(0, 0, dest); - nlr_pop(); - return MP_VM_RETURN_YIELD; - } else { - *ret_val = MP_OBJ_FROM_PTR(nlr.ret_val); - return MP_VM_RETURN_EXCEPTION; - } + *ret_val = mp_call_method_n_kw(0, 0, dest); + return MP_VM_RETURN_YIELD; } } @@ -1325,10 +1344,6 @@ mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t th if (send_value != MP_OBJ_NULL) { mp_load_method(self_in, MP_QSTR_send, dest); dest[2] = send_value; - // TODO: This should have exception wrapping like __next__ case - // above. Not done right away to think how to optimize native - // generators better, see: - // https://github.com/micropython/micropython/issues/2628 *ret_val = mp_call_method_n_kw(1, 0, dest); return MP_VM_RETURN_YIELD; } @@ -1390,7 +1405,7 @@ mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) { args[1] = mp_const_none; // TODO should be globals args[2] = mp_const_none; // TODO should be locals args[3] = fromlist; - args[4] = level; // must be 0; we don't yet support other values + args[4] = level; // TODO lookup __import__ and call that instead of going straight to builtin implementation return mp_builtin___import__(5, args); @@ -1405,7 +1420,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); } @@ -1432,15 +1447,8 @@ mp_obj_t mp_import_from(mp_obj_t module, qstr name) { qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len); mp_local_free(dot_name); - mp_obj_t args[5]; - args[0] = MP_OBJ_NEW_QSTR(dot_name_q); - args[1] = mp_const_none; // TODO should be globals - args[2] = mp_const_none; // TODO should be locals - args[3] = mp_const_true; // Pass sentinel "non empty" value to force returning of leaf module - args[4] = MP_OBJ_NEW_SMALL_INT(0); - - // TODO lookup __import__ and call that instead of going straight to builtin implementation - return mp_builtin___import__(5, args); + // For fromlist, pass sentinel "non empty" value to force returning of leaf module + return mp_import_name(dot_name_q, mp_const_true, MP_OBJ_NEW_SMALL_INT(0)); #else @@ -1454,12 +1462,16 @@ void mp_import_all(mp_obj_t module) { DEBUG_printf("import all %p\n", module); // TODO: Support __all__ - mp_map_t *map = mp_obj_dict_get_map(MP_OBJ_FROM_PTR(mp_obj_module_get_globals(module))); + mp_map_t *map = &mp_obj_module_get_globals(module)->map; for (size_t i = 0; i < map->alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(map, i)) { - qstr name = MP_OBJ_QSTR_VALUE(map->table[i].key); - if (*qstr_str(name) != '_') { - mp_store_name(name, map->table[i].value); + // Entry in module global scope may be generated programmatically + // (and thus be not a qstr for longer names). Avoid turning it in + // qstr if it has '_' and was used exactly to save memory. + const char *name = mp_obj_str_get_str(map->table[i].key); + if (*name != '_') { + qstr qname = mp_obj_str_get_qstr(map->table[i].key); + mp_store_name(qname, map->table[i].value); } } } diff --git a/py/runtime.h b/py/runtime.h index 5e8fda35c1857..c30252a946d26 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -72,24 +72,35 @@ 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 // extra printing method specifically for mp_obj_t's which are integral type int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char, int flags, char fill, int width, int prec); +void mp_arg_check_num_sig(size_t n_args, size_t n_kw, uint32_t sig); void mp_arg_check_num(size_t n_args, mp_map_t *kw_args, size_t n_args_min, size_t n_args_max, bool takes_kw); -void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw); +void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); void mp_arg_parse_all_kw_array(size_t n_pos, size_t n_kw, const mp_obj_t *args, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals); 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); @@ -188,6 +199,7 @@ NORETURN void mp_raise_recursion_depth(void); // helper functions for native/viper code 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); +mp_obj_dict_t *mp_native_swap_globals(mp_obj_dict_t *new_globals); mp_obj_t mp_native_call_function_n_kw(mp_obj_t fun_in, size_t n_args_kw, const mp_obj_t *args); void mp_native_raise(mp_obj_t o); diff --git a/py/runtime0.h b/py/runtime0.h index fb35c8a9f4c0d..33c92830cef8d 100644 --- a/py/runtime0.h +++ b/py/runtime0.h @@ -25,15 +25,18 @@ */ #ifndef MICROPY_INCLUDED_PY_RUNTIME0_H #define MICROPY_INCLUDED_PY_RUNTIME0_H - #include "mpconfig.h" -// These must fit in 8 bits; see scope.h +// The first four must fit in 8 bits, see emitbc.c +// The remaining must fit in 16 bits, see scope.h #define MP_SCOPE_FLAG_VARARGS (0x01) #define MP_SCOPE_FLAG_VARKEYWORDS (0x02) #define MP_SCOPE_FLAG_GENERATOR (0x04) #define MP_SCOPE_FLAG_DEFKWARGS (0x08) #define MP_SCOPE_FLAG_ASYNC (0x10) +#define MP_SCOPE_FLAG_REFGLOBALS (0x20) // used only if native emitter enabled +#define MP_SCOPE_FLAG_HASCONSTS (0x40) // used only if native emitter enabled +#define MP_SCOPE_FLAG_VIPERRET_POS (7) // 3 bits used for viper return type // types for native (viper) function signature #define MP_NATIVE_TYPE_OBJ (0x00) @@ -60,6 +63,7 @@ typedef enum { MP_UNARY_OP_LEN, // __len__ MP_UNARY_OP_HASH, // __hash__; must return a small int MP_UNARY_OP_ABS, // __abs__ + MP_UNARY_OP_INT, // __int__ MP_UNARY_OP_SIZEOF, // for sys.getsizeof() MP_UNARY_OP_NUM_RUNTIME, @@ -112,7 +116,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 +129,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. @@ -146,8 +150,12 @@ typedef enum { } mp_binary_op_t; typedef enum { - MP_F_CONVERT_OBJ_TO_NATIVE = 0, + MP_F_CONST_NONE_OBJ = 0, + MP_F_CONST_FALSE_OBJ, + MP_F_CONST_TRUE_OBJ, + MP_F_CONVERT_OBJ_TO_NATIVE, MP_F_CONVERT_NATIVE_TO_OBJ, + MP_F_NATIVE_SWAP_GLOBALS, MP_F_LOAD_NAME, MP_F_LOAD_GLOBAL, MP_F_LOAD_BUILD_CLASS, @@ -166,10 +174,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,21 +190,23 @@ 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, MP_F_DELETE_GLOBAL, MP_F_NEW_CELL, MP_F_MAKE_CLOSURE_FROM_RAW_CODE, + MP_F_ARG_CHECK_NUM_SIG, MP_F_SETUP_CODE_STATE, MP_F_SMALL_INT_FLOOR_DIVIDE, MP_F_SMALL_INT_MODULO, + MP_F_NATIVE_YIELD_FROM, MP_F_NUMBER_OF, } mp_fun_kind_t; -extern void *const mp_fun_table[MP_F_NUMBER_OF]; +extern const void *const mp_fun_table[MP_F_NUMBER_OF]; #endif // MICROPY_INCLUDED_PY_RUNTIME0_H diff --git a/py/scope.c b/py/scope.c index 98f39d4c6dbbb..1244240c8d3ce 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]; } @@ -64,10 +64,9 @@ void scope_free(scope_t *scope) { m_del(scope_t, scope, 1); } -id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, bool *added) { +id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, scope_kind_t kind) { id_info_t *id_info = scope_find(scope, qst); if (id_info != NULL) { - *added = false; return id_info; } @@ -82,11 +81,10 @@ id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, bool *added) { // handled by the compiler because it adds arguments before compiling the body id_info = &scope->id_info[scope->id_info_len++]; - id_info->kind = 0; + id_info->kind = kind; id_info->flags = 0; id_info->local_num = 0; id_info->qst = qst; - *added = true; return id_info; } @@ -110,9 +108,8 @@ STATIC void scope_close_over_in_parents(scope_t *scope, qstr qst) { assert(scope->parent != NULL); // we should have at least 1 parent for (scope_t *s = scope->parent;; s = s->parent) { assert(s->parent != NULL); // we should not get to the outer scope - bool added; - id_info_t *id = scope_find_or_add_id(s, qst, &added); - if (added) { + id_info_t *id = scope_find_or_add_id(s, qst, ID_INFO_KIND_UNDECIDED); + if (id->kind == ID_INFO_KIND_UNDECIDED) { // variable not previously declared in this scope, so declare it as free and keep searching parents id->kind = ID_INFO_KIND_FREE; } else { @@ -130,21 +127,19 @@ STATIC void scope_close_over_in_parents(scope_t *scope, qstr qst) { } } -void scope_find_local_and_close_over(scope_t *scope, id_info_t *id, qstr qst) { +void scope_check_to_close_over(scope_t *scope, id_info_t *id) { if (scope->parent != NULL) { for (scope_t *s = scope->parent; s->parent != NULL; s = s->parent) { - id_info_t *id2 = scope_find(s, qst); + id_info_t *id2 = scope_find(s, id->qst); if (id2 != NULL) { if (id2->kind == ID_INFO_KIND_LOCAL || id2->kind == ID_INFO_KIND_CELL || id2->kind == ID_INFO_KIND_FREE) { id->kind = ID_INFO_KIND_FREE; - scope_close_over_in_parents(scope, qst); - return; + scope_close_over_in_parents(scope, id->qst); } break; } } } - id->kind = ID_INFO_KIND_GLOBAL_IMPLICIT; } #endif // MICROPY_ENABLE_COMPILER diff --git a/py/scope.h b/py/scope.h index c92a39e5e6711..485a964abe528 100644 --- a/py/scope.h +++ b/py/scope.h @@ -30,6 +30,7 @@ #include "py/emitglue.h" enum { + ID_INFO_KIND_UNDECIDED, ID_INFO_KIND_GLOBAL_IMPLICIT, ID_INFO_KIND_GLOBAL_EXPLICIT, ID_INFO_KIND_LOCAL, // in a function f, written and only referenced by f @@ -41,6 +42,7 @@ enum { ID_FLAG_IS_PARAM = 0x01, ID_FLAG_IS_STAR_PARAM = 0x02, ID_FLAG_IS_DBL_STAR_PARAM = 0x04, + ID_FLAG_VIPER_TYPE_POS = 4, }; typedef struct _id_info_t { @@ -71,11 +73,11 @@ typedef struct _scope_t { struct _scope_t *parent; struct _scope_t *next; mp_parse_node_t pn; + mp_raw_code_t *raw_code; uint16_t source_file; // a qstr uint16_t simple_name; // a qstr - mp_raw_code_t *raw_code; - uint8_t scope_flags; // see runtime0.h - uint8_t emit_options; // see compile.h + uint16_t scope_flags; // see runtime0.h + uint16_t emit_options; // see emitglue.h uint16_t num_pos_args; uint16_t num_kwonly_args; uint16_t num_def_pos_args; @@ -89,9 +91,9 @@ typedef struct _scope_t { scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, mp_uint_t emit_options); void scope_free(scope_t *scope); -id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, bool *added); +id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, scope_kind_t kind); id_info_t *scope_find(scope_t *scope, qstr qstr); id_info_t *scope_find_global(scope_t *scope, qstr qstr); -void scope_find_local_and_close_over(scope_t *scope, id_info_t *id, qstr qst); +void scope_check_to_close_over(scope_t *scope, id_info_t *id); #endif // MICROPY_INCLUDED_PY_SCOPE_H diff --git a/py/sequence.c b/py/sequence.c index e6421fde5ee76..2fcd8401712a7 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 5a8e660fc4128..a94b2b3a574a0 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 26fc065b7d19c..d699d6da61410 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 18cd81e75be47..6b003f6c2843a 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 ae702bb1b69dc..35cbc4e211d53 100644 --- a/py/stream.c +++ b/py/stream.c @@ -99,14 +99,22 @@ const mp_stream_p_t *mp_get_stream_raise(mp_obj_t self_in, int flags) { STATIC mp_obj_t stream_read_generic(size_t n_args, const mp_obj_t *args, byte flags) { // What to do if sz < -1? Python docs don't specify this case. - // CPython does a readall, but here we silently let negatives through, - // and they will cause a MemoryError. + // CPython does a readall, let's do the same. mp_int_t sz; - if (n_args == 1 || args[1] == mp_const_none || ((sz = mp_obj_get_int(args[1])) == -1)) { - return stream_readall(args[0]); - } - const mp_stream_p_t *stream_p = mp_get_stream(args[0]); + if (stream_p->pyserial_read_compatibility) { + // Pyserial defaults to sz=1 if not specified. + if (n_args == 1) { + sz = 1; + } else { + // Pyserial treats negative size as 0. + sz = MAX(0, mp_obj_get_int(args[1])); + } + } else { + if (n_args == 1 || args[1] == mp_const_none || (sz = mp_obj_get_int(args[1])) <= -1) { + return stream_readall(args[0]); + } + } #if MICROPY_PY_BUILTINS_STR_UNICODE if (stream_p->is_text) { @@ -227,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 @@ -264,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); @@ -284,7 +292,7 @@ STATIC mp_obj_t stream_readinto(size_t n_args, const mp_obj_t *args) { // https://docs.python.org/3/library/socket.html#socket.socket.recv_into mp_uint_t len = bufinfo.len; if (n_args > 2) { - if (mp_get_stream(args[0])->pyserial_compatibility) { + if (mp_get_stream(args[0])->pyserial_readinto_compatibility) { mp_raise_ValueError(translate("length argument not allowed for this type")); } len = mp_obj_get_int(args[2]); @@ -297,7 +305,10 @@ STATIC mp_obj_t stream_readinto(size_t n_args, const mp_obj_t *args) { mp_uint_t out_sz = mp_stream_read_exactly(args[0], bufinfo.buf, len, &error); if (error != 0) { if (mp_is_nonblocking_error(error)) { - return mp_const_none; + // pyserial readinto never returns None, just 0. + return mp_get_stream(args[0])->pyserial_dont_return_none_compatibility + ? MP_OBJ_NEW_SMALL_INT(0) + : mp_const_none; } mp_raise_OSError(error); } else { @@ -323,7 +334,10 @@ STATIC mp_obj_t stream_readall(mp_obj_t self_in) { // If we read nothing, return None, just like read(). // Otherwise, return data read so far. if (total_size == 0) { - return mp_const_none; + // pyserial read() never returns None, just b''. + return stream_p->pyserial_dont_return_none_compatibility + ? mp_const_empty_bytes + : mp_const_none; } break; } @@ -387,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. @@ -520,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) { @@ -531,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) { @@ -542,12 +556,12 @@ 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; seek_s.whence = whence; - mp_uint_t res = stream_p->ioctl(stream, MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &mp_stream_errno); + mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &mp_stream_errno); if (res == MP_STREAM_ERROR) { return -1; } @@ -555,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 be6b23d40d147..3aa0245be16d9 100644 --- a/py/stream.h +++ b/py/stream.h @@ -42,6 +42,7 @@ #define MP_STREAM_SET_OPTS (7) // Set stream options #define MP_STREAM_GET_DATA_OPTS (8) // Get data/message options #define MP_STREAM_SET_DATA_OPTS (9) // Set data/message options +#define MP_STREAM_GET_FILENO (10) // Get fileno of underlying file // These poll ioctl values are compatible with Linux #define MP_STREAM_POLL_RD (0x0001) @@ -72,7 +73,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_compatibility: 1; // adjust API to match pyserial more closely + 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); @@ -111,7 +114,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); @@ -119,10 +122,11 @@ mp_obj_t mp_stream_flush(mp_obj_t self); #if MICROPY_STREAMS_POSIX_API // Functions with POSIX-compatible signatures -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); -off_t mp_stream_posix_lseek(mp_obj_t stream, off_t offset, int whence); -int mp_stream_posix_fsync(mp_obj_t stream); +// "stream" is assumed to be a pointer to a concrete object with the stream protocol +ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len); +ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len); +off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence); +int mp_stream_posix_fsync(void *stream); #endif #if MICROPY_STREAMS_NON_BLOCK diff --git a/py/unicode.c b/py/unicode.c index a17dbf969b022..1e41821d51b90 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; @@ -180,7 +182,7 @@ bool utf8_check(const byte *p, size_t len) { for (; p < end; p++) { byte c = *p; if (need) { - if (c >= 0x80) { + if (UTF8_IS_CONT(c)) { need--; } else { // mismatch diff --git a/py/vm.c b/py/vm.c index 13a9980aad2af..615a5503047d2 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() \ @@ -117,32 +117,42 @@ // returns: // 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_EXCEPTION, exception in state[0] +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 { \ + 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 #define DISPATCH() do { \ TRACE(ip); \ MARK_EXC_IP_GLOBAL(); \ goto *entry_table[*ip++]; \ - } while (0) +} while (0) + #define ONE_TRUE_DISPATCH() DISPATCH() + #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 @@ -150,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) @@ -175,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; @@ -197,28 +208,28 @@ run_code_state: ; // loop to execute byte code for (;;) { -dispatch_loop: -#if MICROPY_OPT_COMPUTED_GOTO - DISPATCH(); -#else + dispatch_loop: + #if MICROPY_OPT_COMPUTED_GOTO + ONE_TRUE_DISPATCH(); + #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 @@ -231,28 +242,28 @@ run_code_state: ; 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); @@ -262,21 +273,21 @@ run_code_state: ; 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); @@ -286,7 +297,7 @@ run_code_state: ; } 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))); @@ -298,14 +309,14 @@ run_code_state: ; #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); @@ -315,7 +326,7 @@ run_code_state: ; } 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))); @@ -327,14 +338,14 @@ run_code_state: ; #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(); @@ -348,7 +359,7 @@ run_code_state: ; } 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; } @@ -364,7 +375,7 @@ run_code_state: ; } #endif - ENTRY(MP_BC_LOAD_METHOD): { + ENTRY(MP_BC_LOAD_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_load_method(*sp, qst, sp); @@ -372,7 +383,7 @@ run_code_state: ; DISPATCH(); } - ENTRY(MP_BC_LOAD_SUPER_METHOD): { + ENTRY(MP_BC_LOAD_SUPER_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; sp -= 1; @@ -380,38 +391,38 @@ run_code_state: ; 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()); @@ -419,7 +430,7 @@ run_code_state: ; } #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]); @@ -432,7 +443,7 @@ run_code_state: ; // 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(); @@ -446,7 +457,7 @@ run_code_state: ; } 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; } @@ -464,13 +475,13 @@ run_code_state: ; } #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) { @@ -480,7 +491,7 @@ run_code_state: ; 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) { @@ -490,44 +501,44 @@ run_code_state: ; 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]; @@ -535,13 +546,13 @@ run_code_state: ; 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; @@ -549,7 +560,7 @@ run_code_state: ; 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; @@ -557,7 +568,7 @@ run_code_state: ; 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; @@ -567,7 +578,7 @@ run_code_state: ; 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--; @@ -577,7 +588,7 @@ run_code_state: ; 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(); @@ -591,7 +602,7 @@ run_code_state: ; 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__, @@ -646,12 +657,12 @@ run_code_state: ; 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; @@ -674,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; @@ -683,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); @@ -694,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)) { @@ -743,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; @@ -764,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; @@ -785,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; @@ -793,48 +804,45 @@ 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) { - mp_obj_t stop = POP(); - mp_obj_t start = TOP(); - SET_TOP(mp_obj_new_slice(start, stop, mp_const_none)); - } else { - mp_obj_t step = POP(); - mp_obj_t stop = POP(); - mp_obj_t start = TOP(); - SET_TOP(mp_obj_new_slice(start, stop, step)); + mp_obj_t step = mp_const_none; + if (*ip++ == 3) { + // 3-argument slice includes step + step = POP(); } + mp_obj_t stop = POP(); + mp_obj_t start = TOP(); + SET_TOP(mp_obj_new_slice(start, stop, step)); 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)]; @@ -853,7 +861,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); @@ -861,7 +869,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); @@ -869,13 +877,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(); @@ -883,7 +891,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 @@ -892,7 +900,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 @@ -901,7 +909,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_FUNCTION): { + ENTRY(MP_BC_CALL_FUNCTION) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -935,7 +943,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 @@ -980,7 +988,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_METHOD): { + ENTRY(MP_BC_CALL_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -1018,7 +1026,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 @@ -1063,66 +1071,60 @@ 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) { + unwind_return: + // Search for and execute finally handlers that aren't already active + while (exc_sp >= exc_stack) { + if (!currently_in_except_block && MP_TAGPTR_TAG1(exc_sp->val_sp)) { + // Found a finally handler that isn't active. + // 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; POP_EXC_BLOCK(); + goto dispatch_loop; } -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; - } - 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 - code_state = new_code_state; - *code_state->sp = res; - goto run_code_state; - } + POP_EXC_BLOCK(); + } + 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; @@ -1151,19 +1153,20 @@ unwind_jump:; 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))) { mp_obj_t raise_t = mp_make_raise_obj(t); RAISE(raise_t); \ +} mp_vm_return_kind_t ret_kind; mp_obj_t send_value = POP(); mp_obj_t t_exc = MP_OBJ_NULL; @@ -1212,7 +1215,7 @@ unwind_jump:; } } - ENTRY(MP_BC_IMPORT_NAME): { + ENTRY(MP_BC_IMPORT_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t obj = POP(); @@ -1220,7 +1223,7 @@ unwind_jump:; 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); @@ -1228,30 +1231,30 @@ unwind_jump:; 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(); @@ -1259,41 +1262,41 @@ unwind_jump:; 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(); - fastn[0] = obj; + code_state->state[0] = obj; 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 @@ -1335,8 +1338,8 @@ unwind_jump:; 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 @@ -1344,7 +1347,7 @@ unwind_jump:; } // for loop } else { -exception_handler: + exception_handler: // exception occurred #if MICROPY_PY_SYS_EXC_INFO @@ -1356,7 +1359,7 @@ unwind_jump:; 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) { @@ -1376,9 +1379,9 @@ unwind_jump:; } } -#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. @@ -1469,7 +1472,7 @@ unwind_jump:; 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 @@ -1478,8 +1481,8 @@ unwind_jump:; #endif } else { // propagate exception to higher level - // TODO what to do about ip and sp? they don't really make sense at this point - fastn[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // must put exception here because sp is invalid + // Note: ip and sp don't have usable values at this point + code_state->state[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // put exception here because sp is invalid return MP_VM_RETURN_EXCEPTION; } } diff --git a/py/vmentrytable.h b/py/vmentrytable.h index e01199eee2a5a..0f6c5e96d3ff5 100644 --- a/py/vmentrytable.h +++ b/py/vmentrytable.h @@ -31,88 +31,96 @@ #include "supervisor/linker.h" -static const void *const PLACE_IN_DTCM_DATA(entry_table[256]) = { - [0 ... 255] = &&entry_default, - [MP_BC_LOAD_CONST_FALSE] = &&entry_MP_BC_LOAD_CONST_FALSE, - [MP_BC_LOAD_CONST_NONE] = &&entry_MP_BC_LOAD_CONST_NONE, - [MP_BC_LOAD_CONST_TRUE] = &&entry_MP_BC_LOAD_CONST_TRUE, - [MP_BC_LOAD_CONST_SMALL_INT] = &&entry_MP_BC_LOAD_CONST_SMALL_INT, - [MP_BC_LOAD_CONST_STRING] = &&entry_MP_BC_LOAD_CONST_STRING, - [MP_BC_LOAD_CONST_OBJ] = &&entry_MP_BC_LOAD_CONST_OBJ, - [MP_BC_LOAD_NULL] = &&entry_MP_BC_LOAD_NULL, - [MP_BC_LOAD_FAST_N] = &&entry_MP_BC_LOAD_FAST_N, - [MP_BC_LOAD_DEREF] = &&entry_MP_BC_LOAD_DEREF, - [MP_BC_LOAD_NAME] = &&entry_MP_BC_LOAD_NAME, - [MP_BC_LOAD_GLOBAL] = &&entry_MP_BC_LOAD_GLOBAL, - [MP_BC_LOAD_ATTR] = &&entry_MP_BC_LOAD_ATTR, - [MP_BC_LOAD_METHOD] = &&entry_MP_BC_LOAD_METHOD, - [MP_BC_LOAD_SUPER_METHOD] = &&entry_MP_BC_LOAD_SUPER_METHOD, - [MP_BC_LOAD_BUILD_CLASS] = &&entry_MP_BC_LOAD_BUILD_CLASS, - [MP_BC_LOAD_SUBSCR] = &&entry_MP_BC_LOAD_SUBSCR, - [MP_BC_STORE_FAST_N] = &&entry_MP_BC_STORE_FAST_N, - [MP_BC_STORE_DEREF] = &&entry_MP_BC_STORE_DEREF, - [MP_BC_STORE_NAME] = &&entry_MP_BC_STORE_NAME, - [MP_BC_STORE_GLOBAL] = &&entry_MP_BC_STORE_GLOBAL, - [MP_BC_STORE_ATTR] = &&entry_MP_BC_STORE_ATTR, - [MP_BC_STORE_SUBSCR] = &&entry_MP_BC_STORE_SUBSCR, - [MP_BC_DELETE_FAST] = &&entry_MP_BC_DELETE_FAST, - [MP_BC_DELETE_DEREF] = &&entry_MP_BC_DELETE_DEREF, - [MP_BC_DELETE_NAME] = &&entry_MP_BC_DELETE_NAME, - [MP_BC_DELETE_GLOBAL] = &&entry_MP_BC_DELETE_GLOBAL, - [MP_BC_DUP_TOP] = &&entry_MP_BC_DUP_TOP, - [MP_BC_DUP_TOP_TWO] = &&entry_MP_BC_DUP_TOP_TWO, - [MP_BC_POP_TOP] = &&entry_MP_BC_POP_TOP, - [MP_BC_ROT_TWO] = &&entry_MP_BC_ROT_TWO, - [MP_BC_ROT_THREE] = &&entry_MP_BC_ROT_THREE, - [MP_BC_JUMP] = &&entry_MP_BC_JUMP, - [MP_BC_POP_JUMP_IF_TRUE] = &&entry_MP_BC_POP_JUMP_IF_TRUE, - [MP_BC_POP_JUMP_IF_FALSE] = &&entry_MP_BC_POP_JUMP_IF_FALSE, - [MP_BC_JUMP_IF_TRUE_OR_POP] = &&entry_MP_BC_JUMP_IF_TRUE_OR_POP, - [MP_BC_JUMP_IF_FALSE_OR_POP] = &&entry_MP_BC_JUMP_IF_FALSE_OR_POP, - [MP_BC_SETUP_WITH] = &&entry_MP_BC_SETUP_WITH, - [MP_BC_WITH_CLEANUP] = &&entry_MP_BC_WITH_CLEANUP, - [MP_BC_UNWIND_JUMP] = &&entry_MP_BC_UNWIND_JUMP, - [MP_BC_SETUP_EXCEPT] = &&entry_MP_BC_SETUP_EXCEPT, - [MP_BC_SETUP_FINALLY] = &&entry_MP_BC_SETUP_FINALLY, - [MP_BC_END_FINALLY] = &&entry_MP_BC_END_FINALLY, - [MP_BC_GET_ITER] = &&entry_MP_BC_GET_ITER, - [MP_BC_GET_ITER_STACK] = &&entry_MP_BC_GET_ITER_STACK, - [MP_BC_FOR_ITER] = &&entry_MP_BC_FOR_ITER, - [MP_BC_POP_BLOCK] = &&entry_MP_BC_POP_BLOCK, - [MP_BC_POP_EXCEPT] = &&entry_MP_BC_POP_EXCEPT, - [MP_BC_BUILD_TUPLE] = &&entry_MP_BC_BUILD_TUPLE, - [MP_BC_BUILD_LIST] = &&entry_MP_BC_BUILD_LIST, - [MP_BC_BUILD_MAP] = &&entry_MP_BC_BUILD_MAP, - [MP_BC_STORE_MAP] = &&entry_MP_BC_STORE_MAP, +#if MICROPY_OPT_COMPUTED_GOTO_SAVE_SPACE +#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) +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), #if MICROPY_PY_BUILTINS_SET - [MP_BC_BUILD_SET] = &&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] = &&entry_MP_BC_BUILD_SLICE, + [MP_BC_BUILD_SLICE] = COMPUTE_ENTRY(&& entry_MP_BC_BUILD_SLICE), #endif - [MP_BC_STORE_COMP] = &&entry_MP_BC_STORE_COMP, - [MP_BC_UNPACK_SEQUENCE] = &&entry_MP_BC_UNPACK_SEQUENCE, - [MP_BC_UNPACK_EX] = &&entry_MP_BC_UNPACK_EX, - [MP_BC_MAKE_FUNCTION] = &&entry_MP_BC_MAKE_FUNCTION, - [MP_BC_MAKE_FUNCTION_DEFARGS] = &&entry_MP_BC_MAKE_FUNCTION_DEFARGS, - [MP_BC_MAKE_CLOSURE] = &&entry_MP_BC_MAKE_CLOSURE, - [MP_BC_MAKE_CLOSURE_DEFARGS] = &&entry_MP_BC_MAKE_CLOSURE_DEFARGS, - [MP_BC_CALL_FUNCTION] = &&entry_MP_BC_CALL_FUNCTION, - [MP_BC_CALL_FUNCTION_VAR_KW] = &&entry_MP_BC_CALL_FUNCTION_VAR_KW, - [MP_BC_CALL_METHOD] = &&entry_MP_BC_CALL_METHOD, - [MP_BC_CALL_METHOD_VAR_KW] = &&entry_MP_BC_CALL_METHOD_VAR_KW, - [MP_BC_RETURN_VALUE] = &&entry_MP_BC_RETURN_VALUE, - [MP_BC_RAISE_VARARGS] = &&entry_MP_BC_RAISE_VARARGS, - [MP_BC_YIELD_VALUE] = &&entry_MP_BC_YIELD_VALUE, - [MP_BC_YIELD_FROM] = &&entry_MP_BC_YIELD_FROM, - [MP_BC_IMPORT_NAME] = &&entry_MP_BC_IMPORT_NAME, - [MP_BC_IMPORT_FROM] = &&entry_MP_BC_IMPORT_FROM, - [MP_BC_IMPORT_STAR] = &&entry_MP_BC_IMPORT_STAR, - [MP_BC_LOAD_CONST_SMALL_INT_MULTI ... MP_BC_LOAD_CONST_SMALL_INT_MULTI + 63] = &&entry_MP_BC_LOAD_CONST_SMALL_INT_MULTI, - [MP_BC_LOAD_FAST_MULTI ... MP_BC_LOAD_FAST_MULTI + 15] = &&entry_MP_BC_LOAD_FAST_MULTI, - [MP_BC_STORE_FAST_MULTI ... MP_BC_STORE_FAST_MULTI + 15] = &&entry_MP_BC_STORE_FAST_MULTI, - [MP_BC_UNARY_OP_MULTI ... MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE - 1] = &&entry_MP_BC_UNARY_OP_MULTI, - [MP_BC_BINARY_OP_MULTI ... MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE - 1] = &&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 ccc567d100879..2b78fc5c83ec1 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/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000000000..1c956f0f98122 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,33 @@ +# For string compression +huffman + +# For nvm.toml +cascadetoml +jinja2 +typer + +requests +sh +click +setuptools +cpp-coveralls + +# For docs +Sphinx<4 +sphinx-rtd-theme +recommonmark +sphinx-autoapi +sphinxcontrib-svg2pdfconverter + +# For translate check +polib + +# For pre-commit +pyyaml +astroid +isort +black +mypy + +# For uploading artifacts +awscli diff --git a/shared-bindings/_bleio/Adapter.c b/shared-bindings/_bleio/Adapter.c index 81277fd701e05..5cacfa0691d16 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 ac7e216d83d04..81b9ec31304fa 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 04c667db442ed..56e8a013ffbde 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 2c144c71b95be..d639f2a421590 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 a0751b7e34aed..b69b71d0c91d6 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); @@ -219,6 +219,23 @@ const mp_obj_property_t bleio_characteristic_value_obj = { (mp_obj_t)&mp_const_none_obj }, }; +//| max_length: int +//| """The max length of this characteristic.""" +//| +STATIC mp_obj_t bleio_characteristic_get_max_length(mp_obj_t self_in) { + bleio_characteristic_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return MP_OBJ_NEW_SMALL_INT(common_hal_bleio_characteristic_get_max_length(self)); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_characteristic_get_max_length_obj, bleio_characteristic_get_max_length); + +const mp_obj_property_t bleio_characteristic_max_length_obj = { + .base.type = &mp_type_property, + .proxy = { (mp_obj_t)&bleio_characteristic_get_max_length_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj }, +}; + //| descriptors: Descriptor //| """A tuple of :py:class:`Descriptor` objects related to this characteristic. (read-only)""" //| @@ -330,5 +347,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 e28d61e1f01cf..878d998a2db91 100644 --- a/shared-bindings/_bleio/Characteristic.h +++ b/shared-bindings/_bleio/Characteristic.h @@ -40,7 +40,8 @@ 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_max_length(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 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 4d6c836c1379d..ddc0c42253235 100644 --- a/shared-bindings/_bleio/CharacteristicBuffer.c +++ b/shared-bindings/_bleio/CharacteristicBuffer.c @@ -231,8 +231,8 @@ STATIC const mp_stream_p_t characteristic_buffer_stream_p = { .write = bleio_characteristic_buffer_write, .ioctl = bleio_characteristic_buffer_ioctl, .is_text = false, - // Match PySerial when possible, such as disallowing optional length argument for .readinto() - .pyserial_compatibility = true, + // Disallow readinto() size parameter. + .pyserial_readinto_compatibility = true, }; @@ -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 fe82af098faf4..b714f42dfd03a 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 60f0acf44bfb6..0eee9d70408a2 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 273cb1c1e3e3e..bda381e3d41a2 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 f2a3cbce07d5b..b54a48230b5f0 100644 --- a/shared-bindings/_bleio/PacketBuffer.c +++ b/shared-bindings/_bleio/PacketBuffer.c @@ -44,7 +44,7 @@ //| When we're the server, we ignore all connections besides the first to subscribe to //| notifications.""" //| -//| def __init__(self, characteristic: Characteristic, *, buffer_size: int) -> None: +//| def __init__(self, characteristic: Characteristic, *, buffer_size: int, max_packet_size: Optional[int] = None) -> None: //| """Monitor the given Characteristic. Each time a new value is written to the Characteristic //| add the newly-written bytes to a FIFO buffer. //| @@ -55,14 +55,17 @@ //| It may be a local Characteristic provided by a Peripheral Service, or a remote Characteristic //| in a remote Service that a Central has connected to. //| :param int buffer_size: Size of ring buffer (in packets of the Characteristic's maximum -//| length) that stores incoming packets coming from the peer.""" +//| length) that stores incoming packets coming from the peer. +//| :param int max_packet_size: Maximum size of packets. Overrides value from the characteristic. +//| (Remote characteristics may not have the correct length.)""" //| ... //| STATIC mp_obj_t bleio_packet_buffer_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_characteristic, ARG_buffer_size }; + enum { ARG_characteristic, ARG_buffer_size, ARG_max_packet_size }; static const mp_arg_t allowed_args[] = { { MP_QSTR_characteristic, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_buffer_size, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_max_packet_size, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none}}, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -79,10 +82,15 @@ STATIC mp_obj_t bleio_packet_buffer_make_new(const mp_obj_type_t *type, size_t n mp_raise_TypeError(translate("Expected a Characteristic")); } + size_t max_packet_size = common_hal_bleio_characteristic_get_max_length(characteristic); + if (args[ARG_max_packet_size].u_obj != mp_const_none) { + max_packet_size = mp_obj_get_int(args[ARG_max_packet_size].u_obj); + } + bleio_packet_buffer_obj_t *self = m_new_obj(bleio_packet_buffer_obj_t); self->base.type = &bleio_packet_buffer_type; - common_hal_bleio_packet_buffer_construct(self, MP_OBJ_TO_PTR(characteristic), buffer_size); + common_hal_bleio_packet_buffer_construct(self, MP_OBJ_TO_PTR(characteristic), buffer_size, max_packet_size); return MP_OBJ_FROM_PTR(self); } @@ -95,7 +103,7 @@ STATIC void check_for_deinit(bleio_packet_buffer_obj_t *self) { //| def readinto(self, buf: WriteableBuffer) -> int: //| """Reads a single BLE packet into the ``buf``. Raises an exception if the next packet is longer -//| than the given buffer. Use `packet_size` to read the maximum length of a single packet. +//| than the given buffer. Use `incoming_packet_length` to read the maximum length of a single packet. //| //| :return: number of bytes read and stored into ``buf`` //| :rtype: int""" @@ -133,7 +141,7 @@ STATIC mp_obj_t bleio_packet_buffer_write(mp_uint_t n_args, const mp_obj_t *pos_ enum { ARG_data, ARG_header }; static const mp_arg_t allowed_args[] = { { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, - { MP_QSTR_header, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + { MP_QSTR_header, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none}}, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -147,7 +155,7 @@ STATIC mp_obj_t bleio_packet_buffer_write(mp_uint_t n_args, const mp_obj_t *pos_ mp_buffer_info_t header_bufinfo; header_bufinfo.len = 0; - if (args[ARG_header].u_obj != MP_OBJ_NULL) { + if (args[ARG_header].u_obj != mp_const_none) { mp_get_buffer_raise(args[ARG_header].u_obj, &header_bufinfo, MP_BUFFER_READ); } @@ -179,11 +187,6 @@ STATIC mp_obj_t bleio_packet_buffer_deinit(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_packet_buffer_deinit_obj, bleio_packet_buffer_deinit); -//| packet_size: int -//| """`packet_size` is the same as `incoming_packet_length`. -//| The name `packet_size` is deprecated and -//| will be removed in CircuitPython 6.0.0.""" -//| //| incoming_packet_length: int //| """Maximum length in bytes of a packet we are reading.""" //| @@ -233,9 +236,6 @@ STATIC const mp_rom_map_elem_t bleio_packet_buffer_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&bleio_packet_buffer_readinto_obj) }, { MP_OBJ_NEW_QSTR(MP_QSTR_write), MP_ROM_PTR(&bleio_packet_buffer_write_obj) }, - // .packet_size is now an alias for .incoming_packet_length - // TODO: Remove in 6.0.0. - { MP_OBJ_NEW_QSTR(MP_QSTR_packet_size), MP_ROM_PTR(&bleio_packet_buffer_incoming_packet_length_obj) }, { MP_OBJ_NEW_QSTR(MP_QSTR_incoming_packet_length), MP_ROM_PTR(&bleio_packet_buffer_incoming_packet_length_obj) }, { MP_OBJ_NEW_QSTR(MP_QSTR_outgoing_packet_length), MP_ROM_PTR(&bleio_packet_buffer_outgoing_packet_length_obj) }, }; @@ -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 769e0a0c78a98..b300cb0215fdb 100644 --- a/shared-bindings/_bleio/PacketBuffer.h +++ b/shared-bindings/_bleio/PacketBuffer.h @@ -33,8 +33,8 @@ 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); + size_t buffer_size, size_t max_packet_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_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 4f07890190bb8..5692e3db25c31 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 9aeaf20d331c1..b37cb610972e9 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 2ddf1a7126902..6657c7e73f03c 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 44d11f60d4c1e..b2a35793fbe99 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 fe045f38538e7..2da54c1d5dbb5 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 b10cce67f3cb8..d07e903803404 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 2ef70a64f7de2..b9d68abaed999 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 65ba9b3a5d5df..7f251ef188552 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 c043aa5faeb4f..3e2591621ad29 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 a8a43e1571282..b98a1246009a1 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 498beaf1c952e..2ecf3419003aa 100644 --- a/shared-bindings/_pew/__init__.c +++ b/shared-bindings/_pew/__init__.c @@ -29,6 +29,7 @@ #include "PewPew.h" #include "common-hal/_pew/PewPew.h" + STATIC mp_obj_t get_pressed(void) { pew_obj_t *pew = MP_STATE_VM(pew_singleton); if (!pew) { @@ -41,17 +42,24 @@ STATIC mp_obj_t get_pressed(void) { STATIC MP_DEFINE_CONST_FUN_OBJ_0(get_pressed_obj, get_pressed); +STATIC mp_obj_t get_ticks(void) { + return mp_obj_new_int(pew_get_ticks()); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_0(get_ticks_obj, get_ticks); + + //| """LED matrix driver""" //| STATIC const mp_rom_map_elem_t pew_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__pew) }, { MP_OBJ_NEW_QSTR(MP_QSTR_PewPew), MP_ROM_PTR(&pewpew_type)}, { MP_OBJ_NEW_QSTR(MP_QSTR_get_pressed), MP_ROM_PTR(&get_pressed_obj)}, + { 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 a4b5b5b1b3998..22923e97d58da 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 d410820591846..5e83b9b2d4c63 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 fdd02509c891a..5e87bacab1487 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 0e8c4a37f9eb2..890543d3e9df1 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 612323a4e4b5d..51ed5c3bf6fe6 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 d1e50fa236fe6..55b60953b6d16 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 f173147e31591..0e3f08da59b46 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/_typing/__init__.pyi b/shared-bindings/_typing/__init__.pyi index cc4a0a4391f00..d1bf853f714fa 100644 --- a/shared-bindings/_typing/__init__.pyi +++ b/shared-bindings/_typing/__init__.pyi @@ -13,7 +13,7 @@ import rgbmatrix import ulab ReadableBuffer = Union[ - bytes, bytearray, memoryview, array.array, ulab.array, rgbmatrix.RGBMatrix + bytes, bytearray, memoryview, array.array, ulab.ndarray, rgbmatrix.RGBMatrix ] """Classes that implement the readable buffer protocol @@ -21,24 +21,24 @@ ReadableBuffer = Union[ - `bytearray` - `memoryview` - `array.array` - - `ulab.array` + - `ulab.ndarray` - `rgbmatrix.RGBMatrix` """ WriteableBuffer = Union[ - bytearray, memoryview, array.array, ulab.array, rgbmatrix.RGBMatrix + bytearray, memoryview, array.array, ulab.ndarray, rgbmatrix.RGBMatrix ] """Classes that implement the writeable buffer protocol - `bytearray` - `memoryview` - `array.array` - - `ulab.array` + - `ulab.ndarray` - `rgbmatrix.RGBMatrix` """ AudioSample = Union[ - audiocore.WaveFile, audiocore.RawSample, audiomixer.Mixer, audiomp3.MP3Decoder + audiocore.WaveFile, audiocore.RawSample, audiomixer.Mixer, audiomp3.MP3Decoder, synthio.MidiTrack ] """Classes that implement the audiosample protocol @@ -46,6 +46,7 @@ AudioSample = Union[ - `audiocore.RawSample` - `audiomixer.Mixer` - `audiomp3.MP3Decoder` + - `synthio.MidiTrack` You can play these back with `audioio.AudioOut`, `audiobusio.I2SOut` or `audiopwmio.PWMAudioOut`. """ diff --git a/shared-bindings/adafruit_bus_device/I2CDevice.c b/shared-bindings/adafruit_bus_device/I2CDevice.c index 3c5d33f52d962..ac760a490fa4b 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) { @@ -234,23 +234,24 @@ STATIC mp_obj_t adafruit_bus_device_i2cdevice_write_then_readinto(size_t n_args, mp_obj_t dest[13]; uint8_t num_kws = 2; + uint8_t index = 2; mp_load_method(self->i2c, MP_QSTR_writeto_then_readfrom, dest); - dest[2] = MP_OBJ_NEW_SMALL_INT(self->device_address); - dest[3] = args[ARG_out_buffer].u_obj; - dest[4] = args[ARG_in_buffer].u_obj; - dest[5] = MP_OBJ_NEW_QSTR(MP_QSTR_out_start); - dest[6] = MP_OBJ_NEW_SMALL_INT(args[ARG_out_start].u_int); + dest[index++] = MP_OBJ_NEW_SMALL_INT(self->device_address); + dest[index++] = args[ARG_out_buffer].u_obj; + dest[index++] = args[ARG_in_buffer].u_obj; + dest[index++] = MP_OBJ_NEW_QSTR(MP_QSTR_out_start); + dest[index++] = MP_OBJ_NEW_SMALL_INT(args[ARG_out_start].u_int); if (args[ARG_out_end].u_int != INT_MAX) { - dest[7] = MP_OBJ_NEW_QSTR(MP_QSTR_out_end); - dest[8] = MP_OBJ_NEW_SMALL_INT(args[ARG_out_end].u_int); + dest[index++] = MP_OBJ_NEW_QSTR(MP_QSTR_out_end); + dest[index++] = MP_OBJ_NEW_SMALL_INT(args[ARG_out_end].u_int); num_kws++; } - dest[9] = MP_OBJ_NEW_QSTR(MP_QSTR_in_start); - dest[10] = MP_OBJ_NEW_SMALL_INT(args[ARG_in_start].u_int); + dest[index++] = MP_OBJ_NEW_QSTR(MP_QSTR_in_start); + dest[index++] = MP_OBJ_NEW_SMALL_INT(args[ARG_in_start].u_int); if (args[ARG_in_end].u_int != INT_MAX) { - dest[11] = MP_OBJ_NEW_QSTR(MP_QSTR_in_end); - dest[12] = MP_OBJ_NEW_SMALL_INT(args[ARG_in_end].u_int); + dest[index++] = MP_OBJ_NEW_QSTR(MP_QSTR_in_end); + dest[index++] = MP_OBJ_NEW_SMALL_INT(args[ARG_in_end].u_int); num_kws++; } @@ -271,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 82ef1feb80f3c..36a95b6a2481e 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 e127e39b81670..94901e4a15993 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); @@ -100,13 +100,22 @@ STATIC mp_obj_t adafruit_bus_device_spidevice_make_new(const mp_obj_type_t *type return (mp_obj_t)self; } +//| def __enter__(self) -> busio.SPI: +//| """Starts a SPI transaction by configuring the SPI and asserting chip select.""" +//| ... +//| STATIC mp_obj_t adafruit_bus_device_spidevice_obj___enter__(mp_obj_t self_in) { adafruit_bus_device_spidevice_obj_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_adafruit_bus_device_spidevice_enter(self); - return self->spi; + return common_hal_adafruit_bus_device_spidevice_enter(self); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(adafruit_bus_device_spidevice___enter___obj, adafruit_bus_device_spidevice_obj___enter__); + +//| def __exit__(self) -> None: +//| """Ends a SPI transaction by deasserting chip select. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| STATIC mp_obj_t adafruit_bus_device_spidevice_obj___exit__(size_t n_args, const mp_obj_t *args) { common_hal_adafruit_bus_device_spidevice_exit(MP_OBJ_TO_PTR(args[0])); return mp_const_none; @@ -121,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/SPIDevice.h b/shared-bindings/adafruit_bus_device/SPIDevice.h index 5596b157f0fdd..997e22a6bd18e 100644 --- a/shared-bindings/adafruit_bus_device/SPIDevice.h +++ b/shared-bindings/adafruit_bus_device/SPIDevice.h @@ -44,7 +44,7 @@ extern const mp_obj_type_t adafruit_bus_device_spidevice_type; // Initializes the hardware peripheral. extern void common_hal_adafruit_bus_device_spidevice_construct(adafruit_bus_device_spidevice_obj_t *self, busio_spi_obj_t *spi, digitalio_digitalinout_obj_t *cs, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t extra_clocks); -extern void common_hal_adafruit_bus_device_spidevice_enter(adafruit_bus_device_spidevice_obj_t *self); +extern mp_obj_t common_hal_adafruit_bus_device_spidevice_enter(adafruit_bus_device_spidevice_obj_t *self); extern void common_hal_adafruit_bus_device_spidevice_exit(adafruit_bus_device_spidevice_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BUSDEVICE_SPIDEVICE_H diff --git a/shared-bindings/adafruit_bus_device/__init__.c b/shared-bindings/adafruit_bus_device/__init__.c index e01abcab3f20a..84abbd0c2e6ed 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 634fed2e54bac..60f6b8361168d 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 a121845e3481e..f021e9abc513b 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)]; - - 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; - - 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 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); + + aesio_aes_obj_t *self = m_new_obj(aesio_aes_obj_t); + self->base.type = &aesio_aes_type; + + 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")); + } + 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 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; } - 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); + 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]); - - 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); + 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); + } } - } - common_hal_aesio_aes_rekey(self, key, key_length, iv); - return mp_const_none; + 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")); - } - - 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")); + size_t dest_length) { + if (src_length != dest_length) { + mp_raise_ValueError( + translate("Source and destination buffers must be the same length")); } - 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")); + + 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_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_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); - - common_hal_aesio_aes_encrypt(aes, (uint8_t *)destbufinfo.buf, - destbufinfo.len); - return mp_const_none; + 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); + + memcpy(destbufinfo.buf, srcbufinfo.buf, srcbufinfo.len); + + 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_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); - - common_hal_aesio_aes_decrypt(aes, (uint8_t *)destbufinfo.buf, - destbufinfo.len); - return mp_const_none; + 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); + + memcpy(destbufinfo.buf, srcbufinfo.buf, srcbufinfo.len); + + 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); - - 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; + 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")); + } + + 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 aed24827adb30..9ca0ec047294f 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 e7a56521b9cf6..c1667ec88367c 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 7023c70e5deba..11b96ff240d2c 100644 --- a/shared-bindings/alarm/__init__.c +++ b/shared-bindings/alarm/__init__.c @@ -92,7 +92,7 @@ void validate_objs_are_alarms(size_t n_args, const mp_obj_t *objs) { //| This allows the user to interrupt an existing program with ctrl-C, //| and to edit the files in CIRCUITPY, which would not be possible in true light sleep. //| Thus, to use light sleep and save significant power, -// it may be necessary to disconnect from the host. +//| it may be necessary to disconnect from the host. //| """ //| ... //| @@ -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) }, @@ -217,7 +217,7 @@ STATIC mp_map_elem_t alarm_module_globals_table[] = { STATIC MP_DEFINE_MUTABLE_DICT(alarm_module_globals, alarm_module_globals_table); // Fetch value from module dict. -mp_obj_t alarm_get_wake_alarm(void) { +mp_obj_t shared_alarm_get_wake_alarm(void) { mp_map_elem_t *elem = mp_map_lookup(&alarm_module_globals.map, MP_ROM_QSTR(MP_QSTR_wake_alarm), MP_MAP_LOOKUP); if (elem) { @@ -228,7 +228,7 @@ mp_obj_t alarm_get_wake_alarm(void) { } // Initialize .wake_alarm value. -void alarm_save_wake_alarm(void) { +void shared_alarm_save_wake_alarm(void) { // Equivalent of: // alarm.wake_alarm = alarm mp_map_elem_t *elem = @@ -240,5 +240,10 @@ 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, }; + +extern void port_idle_until_interrupt(void); +MP_WEAK void common_hal_alarm_pretending_deep_sleep(void) { + port_idle_until_interrupt(); +} diff --git a/shared-bindings/alarm/__init__.h b/shared-bindings/alarm/__init__.h index 154f91e265b13..9c85b2e212e2c 100644 --- a/shared-bindings/alarm/__init__.h +++ b/shared-bindings/alarm/__init__.h @@ -40,21 +40,20 @@ extern mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const // call alarm_woken_from_sleep to see if we've been woken by an alarm and if so, // it will exit idle as if deep sleep was exited. extern void common_hal_alarm_set_deep_sleep_alarms(size_t n_alarms, const mp_obj_t *alarms); -// Deep sleep is entered outside of the VM so we omit the `common_hal_` prefix. -extern NORETURN void alarm_enter_deep_sleep(void); + +extern NORETURN void common_hal_alarm_enter_deep_sleep(void); +extern void common_hal_alarm_pretending_deep_sleep(void); // Fetches value from module dict. -extern mp_obj_t alarm_get_wake_alarm(void); +extern mp_obj_t shared_alarm_get_wake_alarm(void); extern void common_hal_alarm_gc_collect(void); extern mp_obj_t common_hal_alarm_get_wake_alarm(void); // Used by wake-up code. -void alarm_save_wake_alarm(void); - +void shared_alarm_save_wake_alarm(void); // True if an alarm is alerting. This is most useful for pretend deep sleep. -extern bool alarm_woken_from_sleep(void); - +extern bool common_hal_alarm_woken_from_sleep(void); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_ALARM___INIT___H diff --git a/shared-bindings/alarm/pin/PinAlarm.c b/shared-bindings/alarm/pin/PinAlarm.c index 89de016bcc06c..04063e89c2708 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 1c9b8d37c5b75..46d6234897e5c 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 4259b71bdf2f5..589229de8e406 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 2cda9355ab0cc..a7756b617eaaf 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); @@ -124,7 +124,7 @@ const mp_obj_property_t analogio_analogin_value_obj = { (mp_obj_t)&mp_const_none_obj}, }; -//| reference_voltage: Optional[float] +//| reference_voltage: float //| """The maximum voltage measurable (also known as the reference voltage) as a //| `float` in Volts.""" //| @@ -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 32f11e08f5db3..9f80416267256 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 787905c3c5cf1..f655228285bf0 100644 --- a/shared-bindings/analogio/AnalogOut.c +++ b/shared-bindings/analogio/AnalogOut.c @@ -42,10 +42,10 @@ //| Example usage:: //| //| import analogio -//| from microcontroller import pin +//| from board import * //| -//| dac = analogio.AnalogOut(pin.PA02) # output on pin PA02 -//| dac.value = 32768 # makes PA02 1.65V""" +//| dac = analogio.AnalogOut(A2) # output on pin A2 +//| dac.value = 32768 # makes A2 1.65V""" //| //| def __init__(self, pin: microcontroller.Pin) -> None: //| """Use the AnalogOut on the given pin. @@ -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 e4e94548b86ac..736afd00192b6 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 1f059f3402709..4e5aebf010eee 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 25b536c34426f..b174cf3a57ca5 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 55527dc73069b..64dcc3bf68bfd 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 a3cc8b07e9373..5a648e1651b22 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 e89fc7e232275..0516bce619755 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 89ccbb88b5aaa..23e246ec2254b 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 df31ee2e07eba..13339222c11da 100644 --- a/shared-bindings/audiocore/RawSample.c +++ b/shared-bindings/audiocore/RawSample.c @@ -30,7 +30,6 @@ #include "py/binary.h" #include "py/objproperty.h" #include "py/runtime.h" -#include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/util.h" #include "shared-bindings/audiocore/RawSample.h" #include "supervisor/shared/translate.h" @@ -83,26 +82,23 @@ STATIC mp_obj_t audioio_rawsample_make_new(const mp_obj_type_t *type, size_t n_a audioio_rawsample_obj_t *self = m_new_obj(audioio_rawsample_obj_t); self->base.type = &audioio_rawsample_type; mp_buffer_info_t bufinfo; - if (mp_get_buffer(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ)) { - uint8_t bytes_per_sample = 1; - bool signed_samples = bufinfo.typecode == 'b' || bufinfo.typecode == 'h'; - if (bufinfo.typecode == 'h' || bufinfo.typecode == 'H') { - bytes_per_sample = 2; - } 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); - } else { - mp_raise_TypeError(translate("buffer must be a bytes-like object")); + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); + uint8_t bytes_per_sample = 1; + bool signed_samples = bufinfo.typecode == 'b' || bufinfo.typecode == 'h'; + if (bufinfo.typecode == 'h' || bufinfo.typecode == 'H') { + bytes_per_sample = 2; + } 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); return MP_OBJ_FROM_PTR(self); } //| def deinit(self) -> None: -//| """Deinitialises the AudioOut and releases any hardware resources for reuse.""" +//| """Deinitialises the RawSample and releases any hardware resources for reuse.""" //| ... //| STATIC mp_obj_t audioio_rawsample_deinit(mp_obj_t self_in) { @@ -189,6 +185,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 61f61a0662a59..71056f30c377d 100644 --- a/shared-bindings/audiocore/RawSample.h +++ b/shared-bindings/audiocore/RawSample.h @@ -27,20 +27,19 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_RAWSAMPLE_H #define MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_RAWSAMPLE_H -#include "common-hal/microcontroller/Pin.h" #include "shared-module/audiocore/RawSample.h" 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 3b4c9fd978a39..5cf6deb2edffd 100644 --- a/shared-bindings/audiocore/WaveFile.c +++ b/shared-bindings/audiocore/WaveFile.c @@ -44,7 +44,7 @@ //| """Load a .wav file for playback with `audioio.AudioOut` or `audiobusio.I2SOut`. //| //| :param typing.BinaryIO file: Already opened wave file -//| :param ~_typing.WriteableBuffer buffer: Optional pre-allocated buffer, that will be split in half and used for double-buffering of the data. If not provided, two 512 byte buffers are allocated internally. +//| :param ~_typing.WriteableBuffer buffer: Optional pre-allocated buffer, that will be split in half and used for double-buffering of the data. If not provided, two 256 byte buffers are allocated internally. //| //| //| Playing a wave file from flash:: @@ -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 f4a17231928b9..29140b4a2b6da 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 b400b945486b1..9fe4a81c4c39a 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 0d479be097594..6a6aeea597814 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 1076ac5ccc1ae..163d7848b47e9 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 a9c58e8645b79..426f756d44d0b 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 293b19b055d5f..95619ca956386 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 a99e1bf62a904..88592a1cb3cd0 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 af00e10551595..c519f7ac40b68 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 83098bc9dd17b..bce4632760190 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 1146bb7981b68..9d0bf676fc992 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 85073bf89cbc6..bdbd14e9e03af 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 36d525e938106..2428cedf16646 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 62e5f56cbb234..29bdd0bb21fdc 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 06571fae1e6a0..c2ebf4fbae73d 100644 --- a/shared-bindings/audiopwmio/PWMAudioOut.c +++ b/shared-bindings/audiopwmio/PWMAudioOut.c @@ -155,8 +155,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiopwmio_pwmaudioout___exit___obj, //| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, `audiomixer.Mixer` or `audiomp3.MP3Decoder`. //| //| The sample itself should consist of 16 bit samples. Microcontrollers with a lower output -//| resolution will use the highest order bits to output. For example, the SAMD21 has a 10 bit -//| DAC that ignores the lowest 6 bits when playing 16 bit samples.""" +//| resolution will use the highest order bits to output.""" //| ... //| STATIC mp_obj_t audiopwmio_pwmaudioout_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -275,5 +274,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 22afc70d38d94..15d1fa940cd72 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 5caea14209dfc..2bafb608a4a9f 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 17005f63a8492..f6be845473aaa 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 1ce4d21e9183c..d950180a23274 100644 --- a/shared-bindings/bitbangio/I2C.h +++ b/shared-bindings/bitbangio/I2C.h @@ -30,17 +30,17 @@ #include "py/obj.h" #include "common-hal/microcontroller/Pin.h" -#include "shared-module/bitbangio/types.h" +#include "shared-module/bitbangio/I2C.h" // Type object used in Python. Should be shared between ports. 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 da94a393e33a5..15cf833242a62 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 ef50db737b1ab..0dbc97512210f 100644 --- a/shared-bindings/bitbangio/OneWire.h +++ b/shared-bindings/bitbangio/OneWire.h @@ -28,16 +28,16 @@ #define MICROPY_INCLUDED_SHARED_BINDINGS_BITBANGIO_ONEWIRE_H #include "common-hal/microcontroller/Pin.h" -#include "shared-module/bitbangio/types.h" +#include "shared-module/bitbangio/OneWire.h" 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 fea88bbd4025e..0f8cb59a60777 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; @@ -224,32 +224,53 @@ STATIC mp_obj_t bitbangio_spi_write(mp_obj_t self_in, mp_obj_t wr_buf) { MP_DEFINE_CONST_FUN_OBJ_2(bitbangio_spi_write_obj, bitbangio_spi_write); -//| def readinto(self, buf: WriteableBuffer) -> None: -//| """Read into the buffer specified by ``buf`` while writing zeroes. -//| Requires the SPI being locked. -//| If the number of bytes to read is 0, nothing happens.""" +//| def readinto(self, buffer: WriteableBuffer, *, start: int = 0, end: Optional[int] = None, write_value: int = 0) -> None: +//| """Read into ``buffer`` while writing ``write_value`` for each byte read. +//| The SPI object must be locked. +//| If the number of bytes to read is 0, nothing happens. +//| +//| :param bytearray buffer: Read data into this buffer +//| :param int start: Start of the slice of ``buffer`` to read into: ``buffer[start:end]`` +//| :param int end: End of the slice; this index is not included. Defaults to ``len(buffer)`` +//| :param int write_value: Value to write while reading.""" //| ... //| -// TODO(tannewt): Add support for start and end kwargs. -STATIC mp_obj_t bitbangio_spi_readinto(size_t n_args, const mp_obj_t *args) { - bitbangio_spi_obj_t *self = MP_OBJ_TO_PTR(args[0]); + +STATIC mp_obj_t bitbangio_spi_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_buffer, ARG_start, ARG_end, ARG_write_value }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_end, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MAX} }, + { MP_QSTR_write_value,MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + }; + bitbangio_spi_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); check_for_deinit(self); + check_lock(self); + 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); + mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE); - if (bufinfo.len == 0) { + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); + int32_t start = args[ARG_start].u_int; + size_t length = bufinfo.len; + normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); + + if (length == 0) { return mp_const_none; } - check_lock(args[0]); - bool ok = shared_module_bitbangio_spi_read(self, bufinfo.buf, bufinfo.len); + + bool ok = shared_module_bitbangio_spi_read(self, ((uint8_t *)bufinfo.buf) + start, length, args[ARG_write_value].u_int); if (!ok) { mp_raise_OSError(MP_EIO); } return mp_const_none; } -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bitbangio_spi_readinto_obj, 2, 2, bitbangio_spi_readinto); +MP_DEFINE_CONST_FUN_OBJ_KW(bitbangio_spi_readinto_obj, 2, bitbangio_spi_readinto); -//| def write_readinto(self, buffer_out: ReadableBuffer, buffer_in: WriteableBuffer, *, out_start: int = 0, out_end: Optional[int] = None, in_start: int = 0, in_end: Optional[int] = None) -> None: +//| def write_readinto(self, buffer_out: ReadableBuffer, buffer_in: ReadableBuffer, *, out_start: int = 0, out_end: Optional[int] = None, in_start: int = 0, in_end: Optional[int] = None) -> None: //| """Write out the data in ``buffer_out`` while simultaneously reading data into ``buffer_in``. +//| The SPI object must be locked. //| The lengths of the slices defined by ``buffer_out[out_start:out_end]`` and ``buffer_in[in_start:in_end]`` //| must be equal. //| If buffer slice lengths are both 0, nothing happens. @@ -274,6 +295,7 @@ STATIC mp_obj_t bitbangio_spi_write_readinto(size_t n_args, const mp_obj_t *pos_ }; bitbangio_spi_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); check_for_deinit(self); + check_lock(self); 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); @@ -299,9 +321,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 +350,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 c4b10b66637d9..2d0d75e4075cd 100644 --- a/shared-bindings/bitbangio/SPI.h +++ b/shared-bindings/bitbangio/SPI.h @@ -30,15 +30,15 @@ #include "py/obj.h" #include "common-hal/microcontroller/Pin.h" -#include "shared-module/bitbangio/types.h" +#include "shared-module/bitbangio/SPI.h" // Type object used in Python. Should be shared between ports. 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); @@ -54,7 +54,7 @@ extern void shared_module_bitbangio_spi_unlock(bitbangio_spi_obj_t *self); extern bool shared_module_bitbangio_spi_write(bitbangio_spi_obj_t *self, const uint8_t *data, size_t len); // Reads in len bytes while outputting zeroes. -extern bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, size_t len); +extern bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_value); // Transfer out len bytes while reading len bytes extern bool shared_module_bitbangio_spi_transfer(bitbangio_spi_obj_t *self, const uint8_t *dout, uint8_t *din, size_t len); diff --git a/shared-bindings/bitbangio/__init__.c b/shared-bindings/bitbangio/__init__.c index e04bdf70115c8..81e9d91a377b1 100644 --- a/shared-bindings/bitbangio/__init__.c +++ b/shared-bindings/bitbangio/__init__.c @@ -36,7 +36,6 @@ #include "shared-bindings/bitbangio/I2C.h" #include "shared-bindings/bitbangio/OneWire.h" #include "shared-bindings/bitbangio/SPI.h" -#include "shared-module/bitbangio/types.h" #include "py/runtime.h" @@ -81,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 new file mode 100644 index 0000000000000..3d352e45c2faa --- /dev/null +++ b/shared-bindings/bitmaptools/__init__.c @@ -0,0 +1,530 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Kevin Matocha + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "shared-bindings/displayio/Bitmap.h" +#include "shared-bindings/bitmaptools/__init__.h" + +#include + +#include "py/binary.h" +#include "py/obj.h" +#include "py/runtime.h" + +//| """Collection of bitmap manipulation tools""" +//| + +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) { + return default_value; + } + return mp_obj_get_int(point); +} + +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) { + *x = x_default; + *y = y_default; + } 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_get_array_fixed_n(xy_tuple, 2, &items); + *x = mp_obj_get_int(items[0]); + *y = mp_obj_get_int(items[1]); + } +} + +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) { + // Helper function for rotozoom + // 1. Extract the clip x,y points from the two clip tuples + // 2. Rearrange values such that clip0_ < clip1_ + // 3. Constrain the clip points to within the bitmap + + extract_tuple(clip0_tuple, clip0_x, clip0_y, 0, 0); + 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) { + int16_t temp_value = *clip0_x; // swap values + *clip0_x = *clip1_x; + *clip1_x = temp_value; + } + if (*clip0_y > *clip1_y) { + int16_t temp_value = *clip0_y; // swap values + *clip0_y = *clip1_y; + *clip1_y = temp_value; + } + + // Constrain the clip window to within the bitmap boundaries + if (*clip0_x < 0) { + *clip0_x = 0; + } + if (*clip0_y < 0) { + *clip0_y = 0; + } + if (*clip0_x > bitmap->width) { + *clip0_x = bitmap->width; + } + if (*clip0_y > bitmap->height) { + *clip0_y = bitmap->height; + } + if (*clip1_x < 0) { + *clip1_x = 0; + } + if (*clip1_y < 0) { + *clip1_y = 0; + } + if (*clip1_x > bitmap->width) { + *clip1_x = bitmap->width; + } + if (*clip1_y > bitmap->height) { + *clip1_y = bitmap->height; + } + +} + +//| +//| def rotozoom( +//| dest_bitmap: displayio.Bitmap, source_bitmap: displayio.Bitmap, +//| *, +//| ox: int, oy: int, dest_clip0: Tuple[int, int], dest_clip1: Tuple[int, int], +//| px: int, py: int, source_clip0: Tuple[int, int], source_clip1: Tuple[int, int], +//| angle: float, scale: float, skip_index: int) -> None: +//| """Inserts the source bitmap region into the destination bitmap with rotation +//| (angle), scale and clipping (both on source and destination bitmaps). +//| +//| :param bitmap dest_bitmap: Destination bitmap that will be copied into +//| :param bitmap source_bitmap: Source bitmap that contains the graphical region to be copied +//| :param int ox: Horizontal pixel location in destination bitmap where source bitmap +//| point (px,py) is placed +//| :param int oy: Vertical pixel location in destination bitmap where source bitmap +//| point (px,py) is placed +//| :param Tuple[int,int] dest_clip0: First corner of rectangular destination clipping +//| region that constrains region of writing into destination bitmap +//| :param Tuple[int,int] dest_clip1: Second corner of rectangular destination clipping +//| region that constrains region of writing into destination bitmap +//| :param int px: Horizontal pixel location in source bitmap that is placed into the +//| destination bitmap at (ox,oy) +//| :param int py: Vertical pixel location in source bitmap that is placed into the +//| destination bitmap at (ox,oy) +//| :param Tuple[int,int] source_clip0: First corner of rectangular source clipping +//| region that constrains region of reading from the source bitmap +//| :param Tuple[int,int] source_clip1: Second corner of rectangular source clipping +//| region that constrains region of reading from the source bitmap +//| :param float angle: Angle of rotation, in radians (positive is clockwise direction) +//| :param float scale: Scaling factor +//| :param int skip_index: Bitmap palette index in the source that will not be copied, +//| 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) { + 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}; + + static const mp_arg_t allowed_args[] = { + {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_source_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, + + {MP_QSTR_ox, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to destination->width / 2 + {MP_QSTR_oy, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to destination->height / 2 + {MP_QSTR_dest_clip0, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + {MP_QSTR_dest_clip1, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + + {MP_QSTR_px, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to source->width / 2 + {MP_QSTR_py, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to source->height / 2 + {MP_QSTR_source_clip0, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + {MP_QSTR_source_clip1, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + + {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_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); + + displayio_bitmap_t *destination = MP_OBJ_TO_PTR(args[ARG_dest_bitmap].u_obj); // the destination bitmap + + displayio_bitmap_t *source = MP_OBJ_TO_PTR(args[ARG_source_bitmap].u_obj); // the source bitmap + + // ensure that the destination bitmap has at least as many `bits_per_value` as the source + if (destination->bits_per_value < source->bits_per_value) { + mp_raise_ValueError(translate("source palette too large")); + } + + // 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); + 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); + 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); + + // 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); + + // Confirm the angle value + 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) { + scale = mp_obj_get_float(args[ARG_scale].u_obj); + } + if (scale < 0) { // ensure scale >= 0 + scale = 1.0; + } + + 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) { + skip_index = 0; + skip_index_none = true; + } else { + skip_index = mp_obj_get_int(args[ARG_skip_index].u_obj); + skip_index_none = false; + } + + 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); + + return mp_const_none; +} + +MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_rotozoom_obj, 0, bitmaptools_obj_rotozoom); +// requires at least 2 arguments (destination bitmap and source bitmap) + +//| +//| def fill_region( +//| dest_bitmap: displayio.Bitmap, +//| x1: int, y1: int, +//| x2: int, y2: int, +//| value: int) -> None: +//| """Draws the color value into the destination bitmap within the +//| rectangular region bounded by (x1,y1) and (x2,y2), exclusive. +//| +//| :param bitmap dest_bitmap: Destination bitmap that will be written into +//| :param int x1: x-pixel position of the first corner of the rectangular fill region +//| :param int y1: y-pixel position of the first corner of the rectangular fill region +//| :param int x2: x-pixel position of the second corner of the rectangular fill region (exclusive) +//| :param int y2: y-pixel position of the second corner of the rectangular fill region (exclusive) +//| :param int value: Bitmap palette index that will be written into the rectangular +//| 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) { + enum {ARG_dest_bitmap, ARG_x1, ARG_y1, ARG_x2, ARG_y2, ARG_value}; + + static const mp_arg_t allowed_args[] = { + {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_x1, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_y1, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_x2, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_y2, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_INT}, + }; + 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); + + displayio_bitmap_t *destination = MP_OBJ_TO_PTR(args[ARG_dest_bitmap].u_obj); // the destination bitmap + + uint32_t value, color_depth; + 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")); + } + + int16_t x1 = args[ARG_x1].u_int; + int16_t y1 = args[ARG_y1].u_int; + int16_t x2 = args[ARG_x2].u_int; + int16_t y2 = args[ARG_y2].u_int; + + common_hal_bitmaptools_fill_region(destination, x1, y1, x2, y2, value); + + return mp_const_none; +} + +MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_fill_region_obj, 0, bitmaptools_obj_fill_region); +// requires all 6 arguments + +//| +//| def draw_line( +//| dest_bitmap: displayio.Bitmap, +//| x1: int, y1: int, +//| x2: int, y2: int, +//| value: int) -> None: +//| """Draws a line into a bitmap specified two endpoints (x1,y1) and (x2,y2). +//| +//| :param bitmap dest_bitmap: Destination bitmap that will be written into +//| :param int x1: x-pixel position of the line's first endpoint +//| :param int y1: y-pixel position of the line's first endpoint +//| :param int x2: x-pixel position of the line's second endpoint +//| :param int y2: y-pixel position of the line's second endpoint +//| :param int value: Bitmap palette index that will be written into the +//| 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) { + enum {ARG_dest_bitmap, ARG_x1, ARG_y1, ARG_x2, ARG_y2, ARG_value}; + + static const mp_arg_t allowed_args[] = { + {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_x1, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_y1, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_x2, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_y2, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_INT}, + }; + 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); + + displayio_bitmap_t *destination = MP_OBJ_TO_PTR(args[ARG_dest_bitmap].u_obj); // the destination bitmap + + uint32_t value, color_depth; + 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")); + } + + int16_t x1 = args[ARG_x1].u_int; + int16_t y1 = args[ARG_y1].u_int; + int16_t x2 = args[ARG_x2].u_int; + 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)) { + mp_raise_ValueError(translate("out of range of target")); + } + + common_hal_bitmaptools_draw_line(destination, x1, y1, x2, y2, value); + + return mp_const_none; +} + +MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_draw_line_obj, 0, bitmaptools_obj_draw_line); +// requires all 6 arguments + +//| def arrayblit(bitmap: displayio.Bitmap, data: ReadableBuffer, x1: int=0, y1: int=0, x2: Optional[int]=None, y2: Optional[int]=None, skip_index:Optional[int]=None) -> None: +//| """Inserts pixels from ``data`` into the rectangle of width×height pixels with the upper left corner at ``(x,y)`` +//| +//| The values from ``data`` are taken modulo the number of color values +//| avalable in the destination bitmap. +//| +//| If x1 or y1 are not specified, they are taken as 0. If x2 or y2 +//| are not specified, or are given as -1, they are taken as the width +//| and height of the image. +//| +//| The coordinates affected by the blit are ``x1 <= x < x2`` and ``y1 <= y < y2``. +//| +//| ``data`` must contain at least as many elements as required. If it +//| contains excess elements, they are ignored. +//| +//| The blit takes place by rows, so the first elements of ``data`` go +//| to the first row, the next elements to the next row, and so on. +//| +//| :param displayio.Bitmap bitmap: A writable bitmap +//| :param ReadableBuffer data: Buffer containing the source pixel values +//| :param int x1: The left corner of the area to blit into (inclusive) +//| :param int y1: The top corner of the area to blit into (inclusive) +//| :param int x2: The right of the area to blit into (exclusive) +//| :param int y2: The bottom corner of the area to blit into (exclusive) +//| :param int skip_index: Bitmap palette index in the source that will not be copied, +//| set to None to copy all pixels +//| """ +//| ... +//| +STATIC mp_obj_t bitmaptools_arrayblit(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_bitmap, ARG_data, ARG_x1, ARG_y1, ARG_x2, ARG_y2, ARG_skip_index }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_x1, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_y1, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_x2, MP_ARG_INT, {.u_int = -1} }, + { MP_QSTR_y2, MP_ARG_INT, {.u_int = -1} }, + { MP_QSTR_skip_index, 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); + + if (!MP_OBJ_IS_TYPE(args[ARG_bitmap].u_obj, &displayio_bitmap_type)) { + mp_raise_TypeError(NULL); + } + displayio_bitmap_t *bitmap = MP_OBJ_TO_PTR(args[ARG_bitmap].u_obj); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_data].u_obj, &bufinfo, MP_BUFFER_READ); + + int x1 = args[ARG_x1].u_int; + int y1 = args[ARG_y1].u_int; + int x2 = args[ARG_x2].u_int == -1 ? bitmap->width : args[ARG_x2].u_int; + int y2 = args[ARG_y2].u_int == -1 ? bitmap->height : args[ARG_y2].u_int; + + if ((x1 < 0) || (y1 < 0) || (x1 > x2) || (y1 > y2) || (x2 > bitmap->width) || (y2 > bitmap->height)) { + mp_raise_IndexError(translate("pixel coordinates out of bounds")); + } + + size_t output_element_count = (x2 - x1) * (y2 - y1); + size_t element_size = mp_binary_get_size('@', bufinfo.typecode, NULL); + size_t input_element_count = bufinfo.len / element_size; + + bool skip_specified = args[ARG_skip_index].u_obj != mp_const_none; + uint32_t skip_index = skip_specified ? mp_obj_get_int(args[ARG_skip_index].u_obj) : 0; + if (input_element_count < output_element_count) { + mp_raise_IndexError(translate("index out of range")); + } + + common_hal_bitmaptools_arrayblit(bitmap, bufinfo.buf, element_size, x1, y1, x2, y2, skip_specified, skip_index); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_arrayblit_obj, 0, bitmaptools_arrayblit); + + +//| def readinto(bitmap: displayio.Bitmap, file: typing.BinaryIO, bits_per_pixel: int, element_size: int = 1, reverse_pixels_in_element: bool = False, swap_bytes_in_element: bool = False, reverse_rows: bool = False) -> None: +//| """Reads from a binary file into a bitmap. +//| +//| The file must be positioned so that it consists of ``bitmap.height`` rows of pixel data, where each row is the smallest multiple of ``element_size`` bytes that can hold ``bitmap.width`` pixels. +//| +//| The bytes in an element can be optionally swapped, and the pixels in an element can be reversed. Also, the +//| row loading direction can be reversed, which may be requires for loading certain bitmap files. +//| +//| This function doesn't parse image headers, but is useful to speed up loading of uncompressed image formats such as PCF glyph data. +//| +//| :param displayio.Bitmap bitmap: A writable bitmap +//| :param typing.BinaryIO file: A file opened in binary mode +//| :param int bits_per_pixel: Number of bits per pixel. Values 1, 2, 4, 8, 16, 24, and 32 are supported; +//| :param int element_size: Number of bytes per element. Values of 1, 2, and 4 are supported, except that 24 ``bits_per_pixel`` requires 1 byte per element. +//| :param bool reverse_pixels_in_element: If set, the first pixel in a word is taken from the Most Signficant Bits; otherwise, it is taken from the Least Significant Bits. +//| :param bool swap_bytes_in_element: If the ``element_size`` is not 1, then reverse the byte order of each element read. +//| :param bool reverse_rows: Reverse the direction of the row loading (required for some bitmap images). +//| """ +//| ... +//| + +STATIC mp_obj_t bitmaptools_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_bitmap, ARG_file, ARG_bits_per_pixel, ARG_element_size, ARG_reverse_pixels_in_element, ARG_swap_bytes_in_element, ARG_reverse_rows }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_file, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_bits_per_pixel, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_element_size, MP_ARG_INT, { .u_int = 1 } }, + { MP_QSTR_reverse_pixels_in_element, MP_ARG_BOOL, { .u_bool = false } }, + { MP_QSTR_swap_bytes_in_element, MP_ARG_BOOL, { .u_bool = false } }, + { MP_QSTR_reverse_rows, MP_ARG_BOOL, { .u_bool = false } }, + }; + + 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); + + if (!MP_OBJ_IS_TYPE(args[ARG_bitmap].u_obj, &displayio_bitmap_type)) { + mp_raise_TypeError(NULL); + } + displayio_bitmap_t *bitmap = MP_OBJ_TO_PTR(args[ARG_bitmap].u_obj); + + if (!MP_OBJ_IS_TYPE(args[ARG_file].u_obj, &mp_type_fileio)) { + mp_raise_TypeError(NULL); + } + pyb_file_obj_t *file = MP_OBJ_TO_PTR(args[ARG_file].u_obj); + + int element_size = args[ARG_element_size].u_int; + if (element_size != 1 && element_size != 2 && element_size != 4) { + mp_raise_ValueError_varg(translate("invalid element_size %d, must be, 1, 2, or 4"), element_size); + } + + int bits_per_pixel = args[ARG_bits_per_pixel].u_int; + switch (bits_per_pixel) { + case 24: + if (element_size != 1) { + mp_raise_ValueError_varg(translate("invalid element size %d for bits_per_pixel %d\n"), element_size, bits_per_pixel); + } + break; + case 1: + case 2: + case 4: + case 8: + case 16: + case 32: + break; + default: + mp_raise_ValueError_varg(translate("invalid bits_per_pixel %d, must be, 1, 4, 8, 16, 24, or 32"), bits_per_pixel); + } + + bool reverse_pixels_in_element = args[ARG_reverse_pixels_in_element].u_bool; + bool swap_bytes_in_element = args[ARG_swap_bytes_in_element].u_bool; + bool reverse_rows = args[ARG_reverse_rows].u_bool; + + common_hal_bitmaptools_readinto(bitmap, file, element_size, bits_per_pixel, reverse_pixels_in_element, swap_bytes_in_element, reverse_rows); + + return mp_const_none; +} + +MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_readinto_obj, 0, bitmaptools_readinto); + +STATIC const mp_rom_map_elem_t bitmaptools_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&bitmaptools_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_rotozoom), MP_ROM_PTR(&bitmaptools_rotozoom_obj) }, + { MP_ROM_QSTR(MP_QSTR_arrayblit), MP_ROM_PTR(&bitmaptools_arrayblit_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill_region), MP_ROM_PTR(&bitmaptools_fill_region_obj) }, + { MP_ROM_QSTR(MP_QSTR_draw_line), MP_ROM_PTR(&bitmaptools_draw_line_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(bitmaptools_module_globals, bitmaptools_module_globals_table); + +const mp_obj_module_t bitmaptools_module = { + .base = {&mp_type_module }, + .globals = (mp_obj_dict_t *)&bitmaptools_module_globals, +}; diff --git a/shared-bindings/bitmaptools/__init__.h b/shared-bindings/bitmaptools/__init__.h new file mode 100644 index 0000000000000..fc1eb59068994 --- /dev/null +++ b/shared-bindings/bitmaptools/__init__.h @@ -0,0 +1,57 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Kevin Matocha + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_BITMAPTOOLS__INIT__H +#define MICROPY_INCLUDED_SHARED_BINDINGS_BITMAPTOOLS__INIT__H + +#include "shared-module/displayio/Bitmap.h" +#include "py/obj.h" +#include "extmod/vfs_fat.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); + +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); + +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); + +void common_hal_bitmaptools_readinto(displayio_bitmap_t *self, pyb_file_obj_t *file, int element_size, int bits_per_pixel, bool reverse_pixels_in_word, bool swap_bytes, bool reverse_rows); +void common_hal_bitmaptools_arrayblit(displayio_bitmap_t *self, void *data, int element_size, int x1, int y1, int x2, int y2, bool skip_specified, uint32_t skip_index); + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_BITMAPTOOLS__INIT__H diff --git a/shared-bindings/bitops/__init__.c b/shared-bindings/bitops/__init__.c new file mode 100644 index 0000000000000..913c8bc8369d6 --- /dev/null +++ b/shared-bindings/bitops/__init__.c @@ -0,0 +1,101 @@ +/* + * This file is part of the Circuit Python project, https://github.com/adafruit/circuitpython + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/bitops/__init__.h" + +//| """Routines for low-level manipulation of binary data""" +//| +//| + +//| def bit_transpose(input: ReadableBuffer, output: WriteableBuffer, width:int = 8) -> WriteableBuffer: +//| """"Transpose" a buffer by assembling each output byte with bits taken from each of ``width`` different input bytes. +//| +//| This can be useful to convert a sequence of pixel values into a single +//| stream of bytes suitable for sending via a parallel conversion method. +//| +//| The number of bytes in the input buffer must be a multiple of the width, +//| and the width can be any value from 2 to 8. If the width is fewer than 8, +//| then the remaining (less significant) bits of the output are set to zero. +//| +//| Let ``stride = len(input)//width``. Then the first byte is made out of the +//| most significant bits of ``[input[0], input[stride], input[2*stride], ...]``. +//| The second byte is made out of the second bits, and so on until the 8th output +//| byte which is made of the first bits of ``input[1], input[1+stride, +//| input[2*stride], ...]``. +//| +//| The required output buffer size is ``len(input) * 8 // width``. +//| +//| Returns the output buffer.""" +//| ... + +STATIC mp_obj_t bit_transpose(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_input, ARG_output, ARG_width }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_input, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_output, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_width, 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); + + int width = args[ARG_width].u_int; + if (width < 2 || width > 8) { + mp_raise_ValueError_varg(translate("width must be from 2 to 8 (inclusive), not %d"), width); + } + + mp_buffer_info_t input_bufinfo; + mp_get_buffer_raise(args[ARG_input].u_obj, &input_bufinfo, MP_BUFFER_READ); + int inlen = input_bufinfo.len; + if (inlen % width != 0) { + mp_raise_ValueError_varg(translate("Input buffer length (%d) must be a multiple of the strand count (%d)"), inlen, width); + } + + mp_buffer_info_t output_bufinfo; + mp_get_buffer_raise(args[ARG_output].u_obj, &output_bufinfo, MP_BUFFER_WRITE); + int avail = output_bufinfo.len; + int outlen = 8 * (inlen / width); + if (avail < outlen) { + mp_raise_ValueError_varg(translate("Output buffer must be at least %d bytes"), outlen); + } + common_hal_bitops_bit_transpose(output_bufinfo.buf, input_bufinfo.buf, inlen, width); + return args[ARG_output].u_obj; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bitops_bit_transpose_obj, 1, bit_transpose); + +STATIC const mp_rom_map_elem_t bitops_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_bitops) }, + { MP_ROM_QSTR(MP_QSTR_bit_transpose), MP_ROM_PTR(&bitops_bit_transpose_obj) }, +}; + +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, +}; diff --git a/shared-bindings/bitops/__init__.h b/shared-bindings/bitops/__init__.h new file mode 100644 index 0000000000000..6654cac5e94cd --- /dev/null +++ b/shared-bindings/bitops/__init__.h @@ -0,0 +1,32 @@ +/* + * This file is part of the Circuit Python project, https://github.com/adafruit/circuitpython + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +#include +#include + +void common_hal_bitops_bit_transpose(uint8_t *result, const uint8_t *src, size_t inlen, size_t num_strands); diff --git a/shared-bindings/board/__init__.c b/shared-bindings/board/__init__.c index 717698408aa68..06b3a899d8089 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 8b456dbd35982..56a6e1b8ae6d3 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 a2d5dbf5073e0..08701938c9153 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 1fae3918199f0..026e1ee968b23 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 9ee5f639b1f0c..a270bab5c9624 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 e47564c8c2de3..e64f17b145bb5 100644 --- a/shared-bindings/busio/SPI.c +++ b/shared-bindings/busio/SPI.c @@ -57,7 +57,7 @@ //| //| """Construct an SPI object on the given pins. //| -//| ..note:: The SPI peripherals allocated in order of desirability, if possible, +//| .. note:: The SPI peripherals allocated in order of desirability, if possible, //| such as highest speed and not shared use first. For instance, on the nRF52840, //| there is a single 32MHz SPI peripheral, and multiple 8MHz peripherals, //| some of which may also be used for I2C. The 32MHz SPI peripheral is returned @@ -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 3a8b6dbc1d264..67ca752bab7c9 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 bf0b7e721d050..05c3addd3e328 100644 --- a/shared-bindings/busio/UART.c +++ b/shared-bindings/busio/UART.c @@ -55,7 +55,7 @@ //| :param ~microcontroller.Pin rs485_dir: the output pin for rs485 direction setting, or ``None`` if rs485 not in use. //| :param bool rs485_invert: rs485_dir pin active high when set. Active low otherwise. //| :param int baudrate: the transmit and receive speed. -//| :param int bits: the number of bits per byte, 7, 8 or 9. +//| :param int bits: the number of bits per byte, 5 to 9. //| :param Parity parity: the parity used for error checking. //| :param int stop: the number of stop bits, 1 or 2. //| :param float timeout: the timeout in seconds to wait for the first character and between subsequent characters when reading. Raises ``ValueError`` if timeout >100 seconds. @@ -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")); } } @@ -82,7 +82,7 @@ STATIC mp_obj_t busio_uart_make_new(const mp_obj_type_t *type, size_t n_args, co // This is needed to avoid crashes with certain UART implementations which // cannot accomodate being moved after creation. (See // https://github.com/adafruit/circuitpython/issues/1056) - busio_uart_obj_t *self = m_new_ll_obj(busio_uart_obj_t); + busio_uart_obj_t *self = m_new_ll_obj_with_finaliser(busio_uart_obj_t); self->base.type = &busio_uart_type; enum { ARG_tx, ARG_rx, ARG_baudrate, ARG_bits, ARG_parity, ARG_stop, ARG_timeout, ARG_receiver_buffer_size, ARG_rts, ARG_cts, ARG_rs485_dir,ARG_rs485_invert}; @@ -103,17 +103,17 @@ 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")); } - uint8_t bits = args[ARG_bits].u_int; - if (bits < 7 || bits > 9) { - mp_raise_ValueError(translate("bits must be 7, 8 or 9")); + if (args[ARG_bits].u_int < 5 || args[ARG_bits].u_int > 9) { + mp_raise_ValueError(translate("bits must be in range 5 to 9")); } + uint8_t bits = args[ARG_bits].u_int; busio_uart_parity_t parity = BUSIO_UART_PARITY_NONE; if (args[ARG_parity].u_obj == &busio_uart_parity_even_obj) { @@ -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; } @@ -387,6 +387,7 @@ const mp_obj_type_t busio_uart_parity_type = { }; STATIC const mp_rom_map_elem_t busio_uart_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&busio_uart_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&busio_uart_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&busio_uart___exit___obj) }, @@ -415,8 +416,8 @@ STATIC const mp_stream_p_t uart_stream_p = { .write = busio_uart_write, .ioctl = busio_uart_ioctl, .is_text = false, - // Match PySerial when possible, such as disallowing optional length argument for .readinto() - .pyserial_compatibility = true, + // Disallow optional length argument for .readinto() + .pyserial_readinto_compatibility = true, }; const mp_obj_type_t busio_uart_type = { @@ -426,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 ce8da1445c697..31b062aee5579 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 04632c2f4a540..e7df331c12bcc 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 fd88ccab00771..a5889650057e5 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 080516d51c5b9..dfe1093a40e30 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 13066764e33b9..e2d21c1df71cb 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 8a39f0f2ae601..370c61ad80659 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 6039631fad071..cddb85c26a584 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 04fa8fc6c2b58..7b85f1722037d 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 fcd2590340994..7f8a8fb96d8a6 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 f29d3ab8ac5df..d9863e8a21e1c 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 e51db26440e73..e03665d6360df 100644 --- a/shared-bindings/countio/Counter.c +++ b/shared-bindings/countio/Counter.c @@ -22,9 +22,8 @@ //| //| For example:: //| +//| import board //| import countio -//| import time -//| from board import * //| //| pin_counter = countio.Counter(board.D1) //| #reset the count after 100 counts @@ -42,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); @@ -116,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; } @@ -141,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 15adbbe2ac5a5..a9eced41a3e8e 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 7046a5e721cc7..f6c0a4221cb9a 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 351e122e0afbe..0874bed550026 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 3d1f9c7cb3765..ebc94fa1a6fd6 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 f8f45b158b671..52ce377e37a6e 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 b9f06fe143c9e..900428b6e4e17 100644 --- a/shared-bindings/displayio/Bitmap.c +++ b/shared-bindings/displayio/Bitmap.c @@ -25,6 +25,7 @@ */ #include "shared-bindings/displayio/Bitmap.h" +#include "shared-module/displayio/Bitmap.h" #include @@ -37,7 +38,20 @@ #include "supervisor/shared/translate.h" //| class Bitmap: -//| """Stores values of a certain size in a 2D array""" +//| """Stores values of a certain size in a 2D array +//| +//| Bitmaps can be treated as read-only buffers. If the number of bits in a pixel is 8, 16, or 32; and the number of bytes +//| per row is a multiple of 4, then the resulting memoryview will correspond directly with the bitmap's contents. Otherwise, +//| the bitmap data is packed into the memoryview with unspecified padding. +//| +//| A Bitmap can be treated as a buffer, allowing its content to be +//| viewed and modified using e.g., with ``ulab.numpy.frombuffer``, +//| but the `displayio.Bitmap.dirty` method must be used to inform +//| displayio when a bitmap was modified through the buffer interface. +//| +//| `bitmaptools.arrayblit` can also be useful to omve data efficiently +//| into a Bitmap. +//| """ //| //| def __init__(self, width: int, height: int, value_count: int) -> None: //| """Create a Bitmap object with the given fixed size. Each pixel stores a value that is used to @@ -150,7 +164,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 +203,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 +213,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 +234,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 +297,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); @@ -291,19 +305,72 @@ STATIC mp_obj_t displayio_bitmap_obj_fill(mp_obj_t self_in, mp_obj_t value_obj) } MP_DEFINE_CONST_FUN_OBJ_2(displayio_bitmap_fill_obj, displayio_bitmap_obj_fill); +//| def dirty(self, x1: int=0, y1: int=0, x2: int=-1, y2:int = -1) -> None: +//| """Inform displayio of bitmap updates done via the buffer +//| protocol. +//| +//| :param int x1: Minimum x-value for rectangular bounding box to be considered as modified +//| :param int y1: Minimum y-value for rectangular bounding box to be considered as modified +//| :param int x2: Maximum x-value (exclusive) for rectangular bounding box to be considered as modified +//| :param int y2: Maximum y-value (exclusive) for rectangular bounding box to be considered as modified +//| +//| If x1 or y1 are not specified, they are taken as 0. If x2 or y2 +//| are not specified, or are given as -1, they are taken as the width +//| and height of the image. Thus, calling dirty() with the +//| default arguments treats the whole bitmap as modified. +//| +//| When a bitmap is modified through the buffer protocol, the +//| display will not be properly updated unless the bitmap is +//| notified of the "dirty rectangle" that encloses all modified +//| pixels.""" +//| ... +//| +STATIC mp_obj_t displayio_bitmap_obj_dirty(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + displayio_bitmap_t *self = MP_OBJ_TO_PTR(pos_args[0]); + enum { ARG_x1, ARG_y1, ARG_x2, ARG_y2 }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_x1, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_y1, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_x2, MP_ARG_INT, {.u_int = -1} }, + { MP_QSTR_y2, MP_ARG_INT, {.u_int = -1} }, + }; + 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); + + displayio_area_t dirty_area = { + .x1 = args[ARG_x1].u_int, + .y1 = args[ARG_y1].u_int, + .x2 = args[ARG_x2].u_int == -1 ? self->width : args[ARG_x2].u_int, + .y2 = args[ARG_y2].u_int == -1 ? self->height : args[ARG_y2].u_int, + }; + + displayio_bitmap_set_dirty_area(self, &dirty_area); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(displayio_bitmap_dirty_obj, 0, displayio_bitmap_obj_dirty); + STATIC const mp_rom_map_elem_t displayio_bitmap_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&displayio_bitmap_height_obj) }, { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&displayio_bitmap_width_obj) }, { MP_ROM_QSTR(MP_QSTR_blit), MP_ROM_PTR(&displayio_bitmap_blit_obj) }, { MP_ROM_QSTR(MP_QSTR_fill), MP_ROM_PTR(&displayio_bitmap_fill_obj) }, + { MP_ROM_QSTR(MP_QSTR_dirty), MP_ROM_PTR(&displayio_bitmap_dirty_obj) }, }; STATIC MP_DEFINE_CONST_DICT(displayio_bitmap_locals_dict, displayio_bitmap_locals_dict_table); +// (the get_buffer protocol returns 0 for success, 1 for failure) +STATIC mp_int_t bitmap_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + displayio_bitmap_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_displayio_bitmap_get_buffer(self, bufinfo, flags); +} + const mp_obj_type_t displayio_bitmap_type = { { &mp_type_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, + .buffer_p = { .get_buffer = bitmap_get_buffer }, }; diff --git a/shared-bindings/displayio/Bitmap.h b/shared-bindings/displayio/Bitmap.h index 00cd98b0a9ea5..458047510a8ba 100644 --- a/shared-bindings/displayio/Bitmap.h +++ b/shared-bindings/displayio/Bitmap.h @@ -34,16 +34,17 @@ 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); +int common_hal_displayio_bitmap_get_buffer(displayio_bitmap_t *self, mp_buffer_info_t *bufinfo, mp_uint_t flags); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_BITMAP_H diff --git a/shared-bindings/displayio/ColorConverter.c b/shared-bindings/displayio/ColorConverter.c index 88d3a1ba8feeb..a5b154b341a1f 100644 --- a/shared-bindings/displayio/ColorConverter.c +++ b/shared-bindings/displayio/ColorConverter.c @@ -30,6 +30,7 @@ #include "lib/utils/context_manager_helpers.h" #include "py/binary.h" +#include "py/enum.h" #include "py/objproperty.h" #include "py/runtime.h" #include "shared-bindings/microcontroller/Pin.h" @@ -39,20 +40,20 @@ //| class ColorConverter: //| """Converts one color format to another.""" //| -//| def __init__(self, *, dither: bool = False) -> None: -//| """Create a ColorConverter object to convert color formats. Only supports RGB888 to RGB565 -//| currently. +//| def __init__(self, *, colorspace: Colorspace=Colorspace.RGB888, dither: bool = False) -> None: +//| """Create a ColorConverter object to convert color formats. +//| +//| :param Colorspace colorspace: The source colorspace, one of the Colorspace constants //| :param bool dither: Adds random noise to dither the output image""" //| ... //| -// TODO(tannewt): Add support for other color formats. -//| STATIC mp_obj_t displayio_colorconverter_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_dither}; + enum { ARG_dither, ARG_input_colorspace }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_dither, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} } + { MP_QSTR_dither, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_input_colorspace, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = (void *)&displayio_colorspace_RGB888_obj} }, }; 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); @@ -60,13 +61,13 @@ STATIC mp_obj_t displayio_colorconverter_make_new(const mp_obj_type_t *type, siz displayio_colorconverter_t *self = m_new_obj(displayio_colorconverter_t); self->base.type = &displayio_colorconverter_type; - common_hal_displayio_colorconverter_construct(self, args[ARG_dither].u_bool); + common_hal_displayio_colorconverter_construct(self, args[ARG_dither].u_bool, (displayio_colorspace_t)cp_enum_value(&displayio_colorspace_type, args[ARG_input_colorspace].u_obj)); return MP_OBJ_FROM_PTR(self); } //| def convert(self, color: int) -> int: -//| """Converts the given RGB888 color to RGB565""" +//| """Converts the given color to RGB565 according to the Colorspace""" //| ... //| STATIC mp_obj_t displayio_colorconverter_obj_convert(mp_obj_t self_in, mp_obj_t color_obj) { @@ -146,5 +147,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 441f7c7aeeeac..018db92c961bf 100644 --- a/shared-bindings/displayio/ColorConverter.h +++ b/shared-bindings/displayio/ColorConverter.h @@ -27,19 +27,20 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_COLORCONVERTER_H #define MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_COLORCONVERTER_H +#include "shared-bindings/displayio/__init__.h" #include "shared-module/displayio/ColorConverter.h" #include "shared-module/displayio/Palette.h" 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, displayio_colorspace_t input_colorspace); +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 8d1a888fe77d3..9d8f8298f6b52 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 f9fbc157c0666..36015cd56f380 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 4f5c47acabcab..6a7c089c9daac 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 14d4f6aa9a7b0..7c2b302ce5de3 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 455d22e7258fe..3ba55a4470048 100644 --- a/shared-bindings/displayio/FourWire.c +++ b/shared-bindings/displayio/FourWire.c @@ -48,7 +48,7 @@ //| The SPI bus and pins are then in use by the display until `displayio.release_displays()` is //| called even after a reload. (It does this so CircuitPython can use the display after your code //| is done.) So, the first time you initialize a display bus in code.py you should call -//| :py:func`displayio.release_displays` first, otherwise it will error after the first code.py run. +//| :py:func:`displayio.release_displays` first, otherwise it will error after the first code.py run. //| //| :param busio.SPI spi_bus: The SPI bus that make up the clock and data lines //| :param microcontroller.Pin command: Data or command pin @@ -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 6f6b528e726ce..300327f7a2009 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 386e270abdae1..75e210db89687 100644 --- a/shared-bindings/displayio/Group.c +++ b/shared-bindings/displayio/Group.c @@ -42,7 +42,7 @@ //| """Create a Group of a given size and scale. Scale is in one dimension. For example, scale=2 //| leads to a layer's pixel being 2x2 pixels when in the group. //| -//| :param int max_size: The maximum group size. +//| :param int max_size: Ignored. Will be removed in 7.x. //| :param int scale: Scale of layer pixels in one dimension. //| :param int x: Initial x position within the parent. //| :param int y: Initial y position within the parent.""" @@ -59,11 +59,6 @@ STATIC mp_obj_t displayio_group_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); - mp_int_t max_size = args[ARG_max_size].u_int; - if (max_size < 1) { - mp_raise_ValueError_varg(translate("%q must be >= 1"), MP_QSTR_max_size); - } - mp_int_t scale = args[ARG_scale].u_int; if (scale < 1) { mp_raise_ValueError_varg(translate("%q must be >= 1"), MP_QSTR_scale); @@ -71,13 +66,13 @@ STATIC mp_obj_t displayio_group_make_new(const mp_obj_type_t *type, size_t n_arg displayio_group_t *self = m_new_obj(displayio_group_t); self->base.type = &displayio_group_type; - common_hal_displayio_group_construct(self, max_size, scale, args[ARG_x].u_int, args[ARG_y].u_int); + common_hal_displayio_group_construct(self, scale, args[ARG_x].u_int, args[ARG_y].u_int); return MP_OBJ_FROM_PTR(self); } // 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); @@ -207,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); @@ -246,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); @@ -278,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 } } @@ -328,6 +326,21 @@ STATIC mp_obj_t group_subscr(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t valu return mp_const_none; } +//| def sort(self, key: function, reverse: bool) -> None: +//| """Sort the members of the group.""" +//| ... +//| +STATIC mp_obj_t displayio_group_obj_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + displayio_group_t *self = native_group(pos_args[0]); + mp_obj_t *args = m_new(mp_obj_t, n_args); + for (size_t i = 1; i < n_args; ++i) { + args[i] = pos_args[i]; + } + args[0] = MP_OBJ_FROM_PTR(self->members); + return mp_obj_list_sort(n_args, pos_args, kw_args); +} +MP_DEFINE_CONST_FUN_OBJ_KW(displayio_group_sort_obj, 1, displayio_group_obj_sort); + STATIC const mp_rom_map_elem_t displayio_group_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_hidden), MP_ROM_PTR(&displayio_group_hidden_obj) }, { MP_ROM_QSTR(MP_QSTR_scale), MP_ROM_PTR(&displayio_group_scale_obj) }, @@ -338,6 +351,7 @@ STATIC const mp_rom_map_elem_t displayio_group_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&displayio_group_index_obj) }, { MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&displayio_group_pop_obj) }, { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&displayio_group_remove_obj) }, + { MP_ROM_QSTR(MP_QSTR_sort), MP_ROM_PTR(&displayio_group_sort_obj) }, }; STATIC MP_DEFINE_CONST_DICT(displayio_group_locals_dict, displayio_group_locals_dict_table); @@ -348,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 942a207f2d15b..266fce959cb5f 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 max_size, 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 5dc4711b3bc2a..ae0948b87950d 100644 --- a/shared-bindings/displayio/I2CDisplay.c +++ b/shared-bindings/displayio/I2CDisplay.c @@ -48,7 +48,7 @@ //| The I2C bus and pins are then in use by the display until `displayio.release_displays()` is //| called even after a reload. (It does this so CircuitPython can use the display after your code //| is done.) So, the first time you initialize a display bus in code.py you should call -//| :py:func`displayio.release_displays` first, otherwise it will error after the first code.py run. +//| :py:func:`displayio.release_displays` first, otherwise it will error after the first code.py run. //| //| :param busio.I2C i2c_bus: The I2C bus that make up the clock and data lines //| :param int device_address: The I2C address of the device @@ -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 37520202e407f..d40cd19d8df0d 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 938e408ab5a65..e41f54edfb5e7 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 9a6c81f8f1fd4..aff3a19db2969 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 c868aea9cf5f3..dc71c0560cdae 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 { @@ -178,9 +180,25 @@ STATIC mp_obj_t displayio_palette_obj_make_opaque(mp_obj_t self_in, mp_obj_t pal } MP_DEFINE_CONST_FUN_OBJ_2(displayio_palette_make_opaque_obj, displayio_palette_obj_make_opaque); +//| def is_transparent(self, palette_index: int) -> bool: +//| """Returns `True` if the palette index is transparent. Returns `False` if opaque.""" +//| ... +//| +STATIC mp_obj_t displayio_palette_obj_is_transparent(mp_obj_t self_in, mp_obj_t palette_index_obj) { + displayio_palette_t *self = MP_OBJ_TO_PTR(self_in); + + mp_int_t palette_index; + if (!mp_obj_get_int_maybe(palette_index_obj, &palette_index)) { + mp_raise_ValueError(translate("palette_index should be an int")); + } + return mp_obj_new_bool(common_hal_displayio_palette_is_transparent(self, palette_index)); +} +MP_DEFINE_CONST_FUN_OBJ_2(displayio_palette_is_transparent_obj, displayio_palette_obj_is_transparent); + STATIC const mp_rom_map_elem_t displayio_palette_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_make_transparent), MP_ROM_PTR(&displayio_palette_make_transparent_obj) }, { MP_ROM_QSTR(MP_QSTR_make_opaque), MP_ROM_PTR(&displayio_palette_make_opaque_obj) }, + { MP_ROM_QSTR(MP_QSTR_is_transparent), MP_ROM_PTR(&displayio_palette_is_transparent_obj) }, }; STATIC MP_DEFINE_CONST_DICT(displayio_palette_locals_dict, displayio_palette_locals_dict_table); @@ -191,5 +209,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 8c9fe11e38112..d9a798016cdce 100644 --- a/shared-bindings/displayio/Palette.h +++ b/shared-bindings/displayio/Palette.h @@ -31,12 +31,13 @@ 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); +bool common_hal_displayio_palette_is_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 30c9d373c803b..084628328d259 100644 --- a/shared-bindings/displayio/ParallelBus.c +++ b/shared-bindings/displayio/ParallelBus.c @@ -49,7 +49,7 @@ //| The parallel bus and pins are then in use by the display until `displayio.release_displays()` //| is called even after a reload. (It does this so CircuitPython can use the display after your //| code is done.) So, the first time you initialize a display bus in code.py you should call -//| :py:func`displayio.release_displays` first, otherwise it will error after the first code.py run. +//| :py:func:`displayio.release_displays` first, otherwise it will error after the first code.py run. //| //| :param microcontroller.Pin data0: The first data pin. The rest are implied //| :param microcontroller.Pin command: Data or command pin @@ -60,7 +60,7 @@ //| ... //| STATIC mp_obj_t displayio_parallelbus_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_data0, ARG_command, ARG_chip_select, ARG_write, ARG_read, ARG_reset }; + enum { ARG_data0, ARG_command, ARG_chip_select, ARG_write, ARG_read, ARG_reset, ARG_frequency }; static const mp_arg_t allowed_args[] = { { MP_QSTR_data0, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, { MP_QSTR_command, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, @@ -68,6 +68,7 @@ STATIC mp_obj_t displayio_parallelbus_make_new(const mp_obj_type_t *type, size_t { MP_QSTR_write, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, { MP_QSTR_read, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, { MP_QSTR_reset, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, + { MP_QSTR_frequency, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 30000000 } }, }; 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); @@ -79,10 +80,10 @@ 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); + common_hal_displayio_parallelbus_construct(self, data0, command, chip_select, write, read, reset, args[ARG_frequency].u_int); return self; } @@ -121,7 +122,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 +139,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 1e74e3a0acf80..1a61aae0af825 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, uint32_t frequency); -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 4d737ecae25c2..0126df885892d 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 d08a38782295a..961b57c674a8e 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 73a08f55679be..dee0d7a68610a 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 0ee1c788360e9..7c8d8a605e36f 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 16d068e2e5d0b..b39e72b946607 100644 --- a/shared-bindings/displayio/__init__.c +++ b/shared-bindings/displayio/__init__.c @@ -26,6 +26,7 @@ #include +#include "py/enum.h" #include "py/obj.h" #include "py/runtime.h" @@ -49,7 +50,6 @@ //| including synchronizing with refresh rates and partial updating.""" //| - //| def release_displays() -> None: //| """Releases any actively used displays so their busses and pins can be used again. This will also //| release the builtin display on boards that have one. You will need to reinitialize it yourself @@ -65,10 +65,48 @@ STATIC mp_obj_t displayio_release_displays(void) { } MP_DEFINE_CONST_FUN_OBJ_0(displayio_release_displays_obj, displayio_release_displays); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB888, DISPLAYIO_COLORSPACE_RGB888); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB565, DISPLAYIO_COLORSPACE_RGB565); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB565_SWAPPED, DISPLAYIO_COLORSPACE_RGB565_SWAPPED); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB555, DISPLAYIO_COLORSPACE_RGB555); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, RGB555_SWAPPED, DISPLAYIO_COLORSPACE_RGB555_SWAPPED); + +//| class Colorspace: +//| """The colorspace for a `ColorConverter` to operate in""" +//| +//| RGB888: Colorspace +//| """The standard 24-bit colorspace. Bits 0-7 are blue, 8-15 are green, and 16-24 are red. (0xRRGGBB)""" +//| +//| RGB565: Colorspace +//| """The standard 16-bit colorspace. Bits 0-4 are blue, bits 5-10 are green, and 11-15 are red (0bRRRRRGGGGGGBBBBB)""" +//| +//| RGB565_SWAPPED: Colorspace +//| """The swapped 16-bit colorspace. First, the high and low 8 bits of the number are swapped, then they are interpreted as for RGB565""" +//| +//| RGB555: Colorspace +//| """The standard 15-bit colorspace. Bits 0-4 are blue, bits 5-9 are green, and 11-14 are red. The top bit is ignored. (0bxRRRRRGGGGGBBBBB)""" +//| +//| RGB555_SWAPPED: Colorspace +//| """The swapped 15-bit colorspace. First, the high and low 8 bits of the number are swapped, then they are interpreted as for RGB555""" +//| +MAKE_ENUM_MAP(displayio_colorspace) { + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB888), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB565), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB565_SWAPPED), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB555), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB555_SWAPPED), +}; +STATIC MP_DEFINE_CONST_DICT(displayio_colorspace_locals_dict, displayio_colorspace_locals_table); + +MAKE_PRINTER(displayio, displayio_colorspace); +MAKE_ENUM_TYPE(displayio, ColorSpace, displayio_colorspace); + + STATIC const mp_rom_map_elem_t displayio_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_displayio) }, { MP_ROM_QSTR(MP_QSTR_Bitmap), MP_ROM_PTR(&displayio_bitmap_type) }, { MP_ROM_QSTR(MP_QSTR_ColorConverter), MP_ROM_PTR(&displayio_colorconverter_type) }, + { MP_ROM_QSTR(MP_QSTR_Colorspace), MP_ROM_PTR(&displayio_colorspace_type) }, { MP_ROM_QSTR(MP_QSTR_Display), MP_ROM_PTR(&displayio_display_type) }, { MP_ROM_QSTR(MP_QSTR_EPaperDisplay), MP_ROM_PTR(&displayio_epaperdisplay_type) }, { MP_ROM_QSTR(MP_QSTR_Group), MP_ROM_PTR(&displayio_group_type) }, @@ -88,5 +126,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/displayio/__init__.h b/shared-bindings/displayio/__init__.h index 4fc666c59866e..31af2ff2bad9e 100644 --- a/shared-bindings/displayio/__init__.h +++ b/shared-bindings/displayio/__init__.h @@ -27,6 +27,7 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H #define MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H +#include "py/enum.h" #include "py/obj.h" typedef enum { @@ -39,6 +40,14 @@ typedef enum { CHIP_SELECT_TOGGLE_EVERY_BYTE } display_chip_select_behavior_t; +typedef enum { + DISPLAYIO_COLORSPACE_RGB888, + DISPLAYIO_COLORSPACE_RGB565, + DISPLAYIO_COLORSPACE_RGB555, + DISPLAYIO_COLORSPACE_RGB565_SWAPPED, + DISPLAYIO_COLORSPACE_RGB555_SWAPPED, +} displayio_colorspace_t; + typedef bool (*display_bus_bus_reset)(mp_obj_t bus); typedef bool (*display_bus_bus_free)(mp_obj_t bus); typedef bool (*display_bus_begin_transaction)(mp_obj_t bus); @@ -48,4 +57,7 @@ typedef void (*display_bus_end_transaction)(mp_obj_t bus); void common_hal_displayio_release_displays(void); +extern const mp_obj_type_t displayio_colorspace_type; +extern const cp_enum_obj_t displayio_colorspace_RGB888_obj; + #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO___INIT___H diff --git a/shared-bindings/dualbank/__init__.c b/shared-bindings/dualbank/__init__.c index 8021ab18b937d..3b267a56fa931 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 8ae2356bbf592..29b124dc58d09 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 f376f35035697..c80d68a8791f8 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 8d1e2ac9c38f3..329e2a893f0f0 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 c41e041cea34e..b482666c26ea3 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 3e58162bf2fad..ae0f3f906f4d8 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 8b0e2b41c9a31..6a2ed02796b70 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 031004d4b48db..0ad8bbbe9badb 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 dca1eb1e89080..367f1ccce48a9 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 557777f50bbec..273f109bf5081 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 f6488bbd75b45..18f9876b772de 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 3e8ea9693d5d4..8856e133acd41 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 f1713589307cb..1b25d342a7fbe 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 087c3539531fe..a3563b7fd61a7 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 4b0d312ae64eb..80901a8c5a132 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 b5c268eb5ccee..9192d61ec53bf 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 3035cfbfe78f9..d3db1b96c9c14 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 e2cb8509d66e2..183b8511c06ed 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/imagecapture/ParallelImageCapture.c b/shared-bindings/imagecapture/ParallelImageCapture.c new file mode 100644 index 0000000000000..ee04dcd5ee421 --- /dev/null +++ b/shared-bindings/imagecapture/ParallelImageCapture.c @@ -0,0 +1,145 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/obj.h" +#include "py/runtime.h" + +#include "lib/utils/context_manager_helpers.h" + +#include "shared-bindings/imagecapture/ParallelImageCapture.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "common-hal/imagecapture/ParallelImageCapture.h" + +//| class ParallelImageCapture: +//| """Capture image frames from a camera with parallel data interface""" +//| +//| def __init__( +//| self, +//| *, +//| data0: microcontroller.Pin, +//| data_count: int=8, +//| clock: microcontroller.Pin, +//| vsync: Optional[microcontroller.Pin], +//| href: Optional[microcontroller.Pin], +//| ): +//| """Create a parallel image capture object +//| :param microcontroller.Pin data0: The first data pin. Additional data pins are assumed to follow this pin directly in the microcontroller's standard pin ordering. +//| :param int data_count: The number of data pins. +//| :param microcontroller.Pin clock: The pixel clock input. +//| :param microcontroller.Pin vsync: The vertical sync input, which has a negative-going pulse at the beginning of each frame. +//| :param microcontroller.Pin href: The horizontal reference input, which is high whenever the camera is transmitting valid pixel information. +//| """ +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture_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_data0, ARG_data_count, ARG_clock, ARG_vsync, ARG_href, + NUM_ARGS }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_data0, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + { MP_QSTR_data_count, MP_ARG_INT | MP_ARG_KW_ONLY, { .u_int = 8 } }, + { MP_QSTR_clock, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + { MP_QSTR_vsync, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + { MP_QSTR_href, MP_ARG_OBJ | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_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 *data0 = validate_obj_is_free_pin(args[ARG_data0].u_obj); + mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); + mcu_pin_obj_t *vsync = validate_obj_is_free_pin_or_none(args[ARG_vsync].u_obj); + mcu_pin_obj_t *href = validate_obj_is_free_pin_or_none(args[ARG_href].u_obj); + + imagecapture_parallelimagecapture_obj_t *self = m_new_obj(imagecapture_parallelimagecapture_obj_t); + self->base.type = &imagecapture_parallelimagecapture_type; + + common_hal_imagecapture_parallelimagecapture_construct(self, data0, clock, vsync, href, args[ARG_data_count].u_int); + + return self; +} + +//| def capture(self, buffer: WriteableBuffer, width: int, height: int, bpp: int=16) -> None: +//| """Capture a single frame into the given buffer""" +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture_capture(mp_obj_t self_in, mp_obj_t buffer) { + imagecapture_parallelimagecapture_obj_t *self = (imagecapture_parallelimagecapture_obj_t *)self_in; + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_RW); + common_hal_imagecapture_parallelimagecapture_capture(self, bufinfo.buf, bufinfo.len); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(imagecapture_parallelimagecapture_capture_obj, imagecapture_parallelimagecapture_capture); + +//| def deinit(self) -> None: +//| """Deinitialize this instance""" +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture_deinit(mp_obj_t self_in) { + imagecapture_parallelimagecapture_obj_t *self = (imagecapture_parallelimagecapture_obj_t *)self_in; + common_hal_imagecapture_parallelimagecapture_deinit(self); + return mp_const_none; +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_1(imagecapture_parallelimagecapture_deinit_obj, imagecapture_parallelimagecapture_deinit); + +//| def __enter__(self) -> ParallelImageCapture: +//| """No-op used in Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes the hardware on context exit. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +STATIC mp_obj_t imagecapture_parallelimagecapture___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_imagecapture_parallelimagecapture_deinit(args[0]); + return mp_const_none; +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(imagecapture_parallelimagecapture___exit___obj, 4, 4, imagecapture_parallelimagecapture___exit__); + + +STATIC const mp_rom_map_elem_t imagecapture_parallelimagecapture_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&imagecapture_parallelimagecapture_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&imagecapture_parallelimagecapture___exit___obj) }, + + { MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&imagecapture_parallelimagecapture_capture_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(imagecapture_parallelimagecapture_locals_dict, imagecapture_parallelimagecapture_locals_dict_table); + +const mp_obj_type_t imagecapture_parallelimagecapture_type = { + { &mp_type_type }, + .name = MP_QSTR_ParallelImageCapture, + .make_new = imagecapture_parallelimagecapture_make_new, + .locals_dict = (mp_obj_dict_t *)&imagecapture_parallelimagecapture_locals_dict, +}; diff --git a/shared-bindings/imagecapture/ParallelImageCapture.h b/shared-bindings/imagecapture/ParallelImageCapture.h new file mode 100644 index 0000000000000..67e05f2bf2a24 --- /dev/null +++ b/shared-bindings/imagecapture/ParallelImageCapture.h @@ -0,0 +1,42 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +#include "common-hal/microcontroller/Pin.h" + +typedef struct imagecapture_parallelimagecapture_obj imagecapture_parallelimagecapture_obj_t; +extern const mp_obj_type_t imagecapture_parallelimagecapture_type; + +void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data_clock, + const mcu_pin_obj_t *vertical_sync, + const mcu_pin_obj_t *horizontal_sync, + int data_count); +void common_hal_imagecapture_parallelimagecapture_deinit(imagecapture_parallelimagecapture_obj_t *self); +bool common_hal_imagecapture_parallelimagecapture_deinited(imagecapture_parallelimagecapture_obj_t *self); +void common_hal_imagecapture_parallelimagecapture_capture(imagecapture_parallelimagecapture_obj_t *self, void *buffer, size_t bufsize); diff --git a/drivers/bus/qspi.h b/shared-bindings/imagecapture/__init__.c similarity index 53% rename from drivers/bus/qspi.h rename to shared-bindings/imagecapture/__init__.c index 81587b08b361c..8f7ce231a676a 100644 --- a/drivers/bus/qspi.h +++ b/shared-bindings/imagecapture/__init__.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2017-2018 Damien P. George + * Copyright (c) 2021 Jeff Epler for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,35 +23,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H -#define MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H -#include "py/mphal.h" +#include -enum { - MP_QSPI_IOCTL_INIT, - MP_QSPI_IOCTL_DEINIT, - MP_QSPI_IOCTL_BUS_ACQUIRE, - MP_QSPI_IOCTL_BUS_RELEASE, -}; +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/imagecapture/ParallelImageCapture.h" -typedef struct _mp_qspi_proto_t { - int (*ioctl)(void *self, uint32_t cmd); - void (*write_cmd_data)(void *self, uint8_t cmd, size_t len, uint32_t data); - void (*write_cmd_addr_data)(void *self, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src); - uint32_t (*read_cmd)(void *self, uint8_t cmd, size_t len); - void (*read_cmd_qaddr_qdata)(void *self, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest); -} mp_qspi_proto_t; +//| """Support for "Parallel capture" interfaces""" +//| -typedef struct _mp_soft_qspi_obj_t { - mp_hal_pin_obj_t cs; - mp_hal_pin_obj_t clk; - mp_hal_pin_obj_t io0; - mp_hal_pin_obj_t io1; - mp_hal_pin_obj_t io2; - mp_hal_pin_obj_t io3; -} mp_soft_qspi_obj_t; +STATIC const mp_rom_map_elem_t imagecapture_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_imagecapture) }, + { MP_ROM_QSTR(MP_QSTR_ParallelImageCapture), MP_ROM_PTR(&imagecapture_parallelimagecapture_type) }, +}; -extern const mp_qspi_proto_t mp_soft_qspi_proto; +STATIC MP_DEFINE_CONST_DICT(imagecapture_module_globals, imagecapture_module_globals_table); -#endif // MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H +const mp_obj_module_t imagecapture_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&imagecapture_module_globals, +}; diff --git a/shared-bindings/imagecapture/__init__.h b/shared-bindings/imagecapture/__init__.h new file mode 100644 index 0000000000000..1e170aa941075 --- /dev/null +++ b/shared-bindings/imagecapture/__init__.h @@ -0,0 +1,27 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once diff --git a/shared-bindings/ipaddress/IPv4Address.c b/shared-bindings/ipaddress/IPv4Address.c index e027f32d65d14..62a54560ef059 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 b45cf3bacb470..46a52a0b23045 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 7ec2984ef7208..f768ec0ba6326 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 a1c31775f9d42..7c2e5c1819ace 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 3883c03c11f46..f5a8ca9cb3990 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 7de8c12874f86..f7684b51a79ff 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 304b9c5a725ba..0a62971821e46 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 b35bae360241e..ea6a1db3ced36 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 bcd9514bf2c76..c677c1a5b6cde 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 c101ba5e0d98b..f6546c25d513b 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 60fcdc3f62f3b..5d9dfddbe2752 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 2a97b54b3de08..289d89017279e 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 e9ddd32bce560..44731c0166693 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 f5c47bb218c77..0bd1d86e20401 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 689d3d7618b13..f3f8d1ab6c73a 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 a353e34aee285..da4f28a1376d8 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 9799e3413d6fd..89b087ddf8130 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 cfcadd98f9419..2c7faf182d3e1 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 bed15c9ede155..0a2ef3389f7bd 100644 --- a/shared-bindings/nvm/ByteArray.c +++ b/shared-bindings/nvm/ByteArray.c @@ -41,7 +41,8 @@ //| Usage:: //| //| import microcontroller -//| microcontroller.nvm[0:3] = b\"\xcc\x10\x00\"""" +//| microcontroller.nvm[0:3] = b"\xcc\x10\x00" +//| """ //| //| def __init__(self) -> None: @@ -60,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 } } @@ -93,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)) { @@ -103,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) { @@ -136,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 9375bcb857fb0..9b74a4a3f3e8d 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 e9784bd187475..dffc4cda89cab 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 8b9b389111be5..798f3c361f6d7 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 8394890def7f1..f6f0a25c937e2 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 07fa5cebb973f..dd6ca83fbe5f8 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 523869d55bf4b..da4c6ba2fe94a 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 38a70b1a27979..a71ffd515f71b 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 3e44a147912a7..18a5d3f3e57a0 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 e28a3c2df4b90..09d01fded75ef 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 2b787df4f098c..61614889fb385 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 49dc555fe3bd5..dce58a63e0d96 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 bfe9635f0181d..44a07fafc6bb4 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 da07555928ee2..01b5bf77acc83 100644 --- a/shared-bindings/pwmio/PWMOut.c +++ b/shared-bindings/pwmio/PWMOut.c @@ -102,14 +102,34 @@ STATIC mp_obj_t pwmio_pwmout_make_new(const mp_obj_type_t *type, size_t n_args, pwmio_pwmout_obj_t *self = m_new_obj(pwmio_pwmout_obj_t); self->base.type = &pwmio_pwmout_type; pwmout_result_t result = common_hal_pwmio_pwmout_construct(self, pin, duty_cycle, frequency, variable_frequency); - if (result == PWMOUT_INVALID_PIN) { - mp_raise_ValueError(translate("Invalid pin")); - } else if (result == PWMOUT_INVALID_FREQUENCY) { - mp_raise_ValueError(translate("Invalid PWM frequency")); - } else if (result == PWMOUT_ALL_TIMERS_ON_PIN_IN_USE) { - mp_raise_ValueError(translate("All timers for this pin are in use")); - } else if (result == PWMOUT_ALL_TIMERS_IN_USE) { - mp_raise_RuntimeError(translate("All timers in use")); + switch (result) { + case PWMOUT_OK: + break; + case PWMOUT_INVALID_PIN: + mp_raise_ValueError(translate("Invalid pin")); + break; + case PWMOUT_INVALID_FREQUENCY: + mp_raise_ValueError(translate("Invalid PWM frequency")); + break; + case PWMOUT_INVALID_FREQUENCY_ON_PIN: + mp_raise_ValueError(translate("Frequency must match existing PWMOut using this timer")); + break; + case PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE: + mp_raise_ValueError(translate("Cannot vary frequency on a timer that is already in use")); + break; + case PWMOUT_ALL_TIMERS_ON_PIN_IN_USE: + mp_raise_ValueError(translate("All timers for this pin are in use")); + break; + case PWMOUT_ALL_TIMERS_IN_USE: + mp_raise_RuntimeError(translate("All timers in use")); + break; + case PWMOUT_ALL_CHANNELS_IN_USE: + mp_raise_RuntimeError(translate("All channels in use")); + break; + default: + case PWMOUT_INITIALIZATION_ERROR: + mp_raise_RuntimeError(translate("Could not start PWM")); + break; } return MP_OBJ_FROM_PTR(self); @@ -174,8 +194,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 +231,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 +261,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 1a99914ea577f..f4d205b215529 100644 --- a/shared-bindings/pwmio/PWMOut.h +++ b/shared-bindings/pwmio/PWMOut.h @@ -32,24 +32,28 @@ extern const mp_obj_type_t pwmio_pwmout_type; -typedef enum { +typedef enum pwmout_result_t { PWMOUT_OK, PWMOUT_INVALID_PIN, PWMOUT_INVALID_FREQUENCY, + PWMOUT_INVALID_FREQUENCY_ON_PIN, + PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE, PWMOUT_ALL_TIMERS_ON_PIN_IN_USE, - PWMOUT_ALL_TIMERS_IN_USE + PWMOUT_ALL_TIMERS_IN_USE, + PWMOUT_ALL_CHANNELS_IN_USE, + PWMOUT_INITIALIZATION_ERROR, } 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 a513837034549..bf4ba31ddd4e1 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 35756eef16791..e3ac4cdc6920c 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 30b72dffd6437..e71bae9f59818 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,12 +435,13 @@ 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; } *bufinfo = self->bufinfo; + bufinfo->typecode = 'H'; return 0; } @@ -442,5 +451,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 4eb3c04b27f0e..127f920da1a64 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 7f0576652a989..451163dbecb05 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 8b0badbe82cad..b27e601c2650f 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 f70632aefbe62..51bf7bd9f6133 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 cd967baa42a42..cdc7742bc1cdc 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 4a792484d6e05..3380a2e6a3889 100644 --- a/shared-bindings/rtc/RTC.c +++ b/shared-bindings/rtc/RTC.c @@ -98,7 +98,13 @@ const mp_obj_property_t rtc_rtc_datetime_obj = { //| """The RTC calibration value as an `int`. //| //| A positive value speeds up the clock and a negative value slows it down. -//| Range and value is hardware specific, but one step is often approximately 1 ppm.""" +//| Range and value is hardware specific, but one step is often approximately 1 ppm:: +//| +//| import rtc +//| import time +//| +//| r = rtc.RTC() +//| r.calibration = 1""" //| STATIC mp_obj_t rtc_rtc_obj_get_calibration(mp_obj_t self_in) { int calibration = common_hal_rtc_get_calibration(); @@ -129,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 baa9c95e142da..1071fa0eabfb4 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 975f8b09532d7..612203b56d583 100644 --- a/shared-bindings/sdcardio/SDCard.c +++ b/shared-bindings/sdcardio/SDCard.c @@ -55,6 +55,12 @@ //| Data transfers use the specified baurate (rounded down to one that is supported by //| the microcontroller) //| +//| .. important:: +//| If the same SPI bus is shared with other peripherals, it is important that +//| the SD card be initialized before accessing any other peripheral on the bus. +//| Failure to do so can prevent the SD card from being recognized until it is +//| powered off or re-inserted. +//| //| Example usage: //| //| .. code-block:: python @@ -78,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); @@ -102,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); @@ -113,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; } @@ -134,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); @@ -158,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); @@ -179,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 746aa5588ef00..e798ad095453f 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 aba414cd63135..468c89821baf1 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 7f62ee7a65c85..cd302f4de771f 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 b88e5c3a968a8..98867fc1218b7 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 e8f4e970a2260..713807745b5c3 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 d1f728c61bf1b..d3d3e14919801 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 799bf28afaf61..336b11225101c 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 0074173405314..642656bbfae10 100644 --- a/shared-bindings/socketpool/Socket.c +++ b/shared-bindings/socketpool/Socket.c @@ -3,8 +3,8 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2014 Damien P. George - * 2018 Nick Moore for Adafruit Industries + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries + * Copyright (c) 2021 Lucian Copeland for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -64,6 +64,25 @@ STATIC mp_obj_t socketpool_socket___exit__(size_t n_args, const mp_obj_t *args) } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socketpool_socket___exit___obj, 4, 4, socketpool_socket___exit__); +//| def accept(self) -> Tuple[Socket, Tuple[str, int]]: +//| """Accept a connection on a listening socket of type SOCK_STREAM, +//| creating a new socket of type SOCK_STREAM. +//| Returns a tuple of (new_socket, remote_address)""" +//| +STATIC mp_obj_t socketpool_socket_accept(mp_obj_t self_in) { + socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); + uint8_t ip[4]; + uint32_t 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); + tuple_contents[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); + return mp_obj_new_tuple(2, tuple_contents); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(socketpool_socket_accept_obj, socketpool_socket_accept); + //| def bind(self, address: Tuple[str, int]) -> None: //| """Bind a socket to an address //| @@ -77,10 +96,13 @@ 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")); + } - bool ok = common_hal_socketpool_socket_bind(self, host, hostlen, port); + bool ok = common_hal_socketpool_socket_bind(self, host, hostlen, (uint32_t)port); if (!ok) { mp_raise_ValueError(translate("Error: Failure to bind")); } @@ -89,41 +111,6 @@ STATIC mp_obj_t socketpool_socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_bind_obj, socketpool_socket_bind); -//| def listen(self, backlog: int) -> None: -//| """Set socket to listen for incoming connections -//| -//| :param ~int backlog: length of backlog queue for waiting connetions""" -//| ... -//| -STATIC mp_obj_t socketpool_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { - socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); - - int backlog = mp_obj_get_int(backlog_in); - - common_hal_socketpool_socket_listen(self, backlog); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_listen_obj, socketpool_socket_listen); - -//| def accept(self) -> Tuple[Socket, Tuple[str, int]]: -//| """Accept a connection on a listening socket of type SOCK_STREAM, -//| creating a new socket of type SOCK_STREAM. -//| Returns a tuple of (new_socket, remote_address)""" -//| -STATIC mp_obj_t socketpool_socket_accept(mp_obj_t self_in) { - socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); - uint8_t ip[4]; - uint 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); - tuple_contents[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); - return mp_obj_new_tuple(2, tuple_contents); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(socketpool_socket_accept_obj, socketpool_socket_accept); - //| def close(self) -> None: //| """Closes this Socket and makes its resources available to its SocketPool.""" //| @@ -147,10 +134,13 @@ 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")); + } - bool ok = common_hal_socketpool_socket_connect(self, host, hostlen, port); + bool ok = common_hal_socketpool_socket_connect(self, host, hostlen, (uint32_t)port); if (!ok) { mp_raise_OSError(0); } @@ -159,31 +149,47 @@ STATIC mp_obj_t socketpool_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_connect_obj, socketpool_socket_connect); -//| def send(self, bytes: ReadableBuffer) -> int: -//| """Send some bytes to the connected remote address. -//| Suits sockets of type SOCK_STREAM +//| def listen(self, backlog: int) -> None: +//| """Set socket to listen for incoming connections //| -//| :param ~bytes bytes: some bytes to send""" +//| :param ~int backlog: length of backlog queue for waiting connetions""" //| ... //| -STATIC mp_obj_t socketpool_socket_send(mp_obj_t self_in, mp_obj_t buf_in) { +STATIC mp_obj_t socketpool_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { + socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); + + int backlog = mp_obj_get_int(backlog_in); + + common_hal_socketpool_socket_listen(self, backlog); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_listen_obj, socketpool_socket_listen); + +//| def recvfrom_into(self, buffer: WriteableBuffer) -> Tuple[int, Tuple[str, int]]: +//| """Reads some bytes from a remote address. +//| +//| Returns a tuple containing +//| * the number of bytes received into the given buffer +//| * a remote_address, which is a tuple of ip address and port number +//| +//| :param object buffer: buffer to read into""" +//| ... +//| +STATIC mp_obj_t socketpool_socket_recvfrom_into(mp_obj_t self_in, mp_obj_t data_in) { socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); - if (common_hal_socketpool_socket_get_closed(self)) { - // Bad file number. - mp_raise_OSError(MP_EBADF); - } - if (!common_hal_socketpool_socket_get_connected(self)) { - mp_raise_BrokenPipeError(); - } mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - mp_int_t ret = common_hal_socketpool_socket_send(self, bufinfo.buf, bufinfo.len); - if (ret == -1) { - mp_raise_BrokenPipeError(); - } - return mp_obj_new_int_from_uint(ret); + mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_WRITE); + + 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); + 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); + return mp_obj_new_tuple(2, tuple_contents); } -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_send_obj, socketpool_socket_send); +STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_recvfrom_into_obj, socketpool_socket_recvfrom_into); //| def recv_into(self, buffer: WriteableBuffer, bufsize: int) -> int: //| """Reads some bytes from the connected remote address, writing @@ -199,7 +205,6 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_send_obj, socketpool_socket_s //| :param int bufsize: optionally, a maximum number of bytes to read.""" //| ... //| - STATIC mp_obj_t socketpool_socket_recv_into(size_t n_args, const mp_obj_t *args) { socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(args[0]); if (common_hal_socketpool_socket_get_closed(self)) { @@ -227,11 +232,37 @@ 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); +//| def send(self, bytes: ReadableBuffer) -> int: +//| """Send some bytes to the connected remote address. +//| Suits sockets of type SOCK_STREAM +//| +//| :param ~bytes bytes: some bytes to send""" +//| ... +//| +STATIC mp_obj_t socketpool_socket_send(mp_obj_t self_in, mp_obj_t buf_in) { + socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (common_hal_socketpool_socket_get_closed(self)) { + // Bad file number. + mp_raise_OSError(MP_EBADF); + } + if (!common_hal_socketpool_socket_get_connected(self)) { + mp_raise_BrokenPipeError(); + } + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); + mp_int_t ret = common_hal_socketpool_socket_send(self, bufinfo.buf, bufinfo.len); + if (ret == -1) { + mp_raise_BrokenPipeError(); + } + return mp_obj_new_int_from_uint(ret); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_send_obj, socketpool_socket_send); + //| def sendto(self, bytes: ReadableBuffer, address: Tuple[str, int]) -> int: //| """Send some bytes to a specific address. //| Suits sockets of type SOCK_DGRAM @@ -240,7 +271,6 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socketpool_socket_recv_into_obj, 2, 3 //| :param ~tuple address: tuple of (remote_address, remote_port)""" //| ... //| - STATIC mp_obj_t socketpool_socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_in) { socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); @@ -252,10 +282,13 @@ 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")); + } - mp_int_t ret = common_hal_socketpool_socket_sendto(self, host, hostlen, port, bufinfo.buf, bufinfo.len); + mp_int_t ret = common_hal_socketpool_socket_sendto(self, host, hostlen, (uint32_t)port, bufinfo.buf, bufinfo.len); if (!ret) { mp_raise_OSError(0); } @@ -264,37 +297,28 @@ STATIC mp_obj_t socketpool_socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_ } STATIC MP_DEFINE_CONST_FUN_OBJ_3(socketpool_socket_sendto_obj, socketpool_socket_sendto); -//| def recvfrom_into(self, buffer: WriteableBuffer) -> Tuple[int, Tuple[str, int]]: -//| """Reads some bytes from a remote address. -//| -//| Returns a tuple containing -//| * the number of bytes received into the given buffer -//| * a remote_address, which is a tuple of ip address and port number +//| def setblocking(self, flag: bool) -> Optional[int]: +//| """Set the blocking behaviour of this socket. //| -//| :param object buffer: buffer to read into""" +//| :param ~bool flag: False means non-blocking, True means block indefinitely.""" //| ... //| -STATIC mp_obj_t socketpool_socket_recvfrom_into(mp_obj_t self_in, mp_obj_t data_in) { +// method socket.setblocking(flag) +STATIC mp_obj_t socketpool_socket_setblocking(mp_obj_t self_in, mp_obj_t blocking) { socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_WRITE); - - 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); - 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); - return mp_obj_new_tuple(2, tuple_contents); + if (mp_obj_is_true(blocking)) { + common_hal_socketpool_socket_settimeout(self, -1); + } else { + common_hal_socketpool_socket_settimeout(self, 0); + } + return mp_const_none; } -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_recvfrom_into_obj, socketpool_socket_recvfrom_into); +STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_setblocking_obj, socketpool_socket_setblocking); // //| def setsockopt(self, level: int, optname: int, value: int) -> None: // //| """Sets socket options""" // //| ... // //| - // STATIC mp_obj_t socketpool_socket_setsockopt(size_t n_args, const mp_obj_t *args) { // // mod_network_socket_obj_t *self = MP_OBJ_TO_PTR(args[0]); @@ -324,13 +348,13 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_recvfrom_into_obj, socketpool // } // STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socketpool_socket_setsockopt_obj, 4, 4, socketpool_socket_setsockopt); + //| def settimeout(self, value: int) -> None: //| """Set the timeout value for this socket. //| //| :param ~int value: timeout in seconds. 0 means non-blocking. None means block indefinitely.""" //| ... //| - STATIC mp_obj_t socketpool_socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t timeout_ms; @@ -348,24 +372,6 @@ STATIC mp_obj_t socketpool_socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_ } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_settimeout_obj, socketpool_socket_settimeout); -// //| def setblocking(self, flag: bool) -> Optional[int]: -// //| """Set the blocking behaviour of this socket. -// //| -// //| :param ~bool flag: False means non-blocking, True means block indefinitely.""" -// //| ... -// //| - -// // method socket.setblocking(flag) -// STATIC mp_obj_t socketpool_socket_setblocking(mp_obj_t self_in, mp_obj_t blocking) { -// // if (mp_obj_is_true(blocking)) { -// // return socket_settimeout(self_in, mp_const_none); -// // } else { -// // return socket_settimeout(self_in, MP_OBJ_NEW_SMALL_INT(0)); -// // } -// return mp_const_none; -// } -// STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_setblocking_obj, socketpool_socket_setblocking); - //| def __hash__(self) -> int: //| """Returns a hash for the Socket.""" //| ... @@ -373,7 +379,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_settimeout_obj, socketpool_so STATIC mp_obj_t socketpool_socket_unary_op(mp_unary_op_t op, mp_obj_t self_in) { switch (op) { case MP_UNARY_OP_HASH: { - return MP_OBJ_NEW_SMALL_INT(common_hal_socketpool_socket_get_hash(MP_OBJ_TO_PTR(self_in))); + return mp_obj_id(self_in); } default: return MP_OBJ_NULL; // op not supported @@ -384,19 +390,19 @@ STATIC const mp_rom_map_elem_t socketpool_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&socketpool_socket___exit___obj) }, { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&socketpool_socket_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&socketpool_socket_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&socketpool_socket_bind_obj) }, - { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&socketpool_socket_listen_obj) }, { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&socketpool_socket_accept_obj) }, + { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&socketpool_socket_bind_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&socketpool_socket_close_obj) }, { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&socketpool_socket_connect_obj) }, - { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&socketpool_socket_send_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socketpool_socket_sendto_obj) }, + { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&socketpool_socket_listen_obj) }, { MP_ROM_QSTR(MP_QSTR_recvfrom_into), MP_ROM_PTR(&socketpool_socket_recvfrom_into_obj) }, { MP_ROM_QSTR(MP_QSTR_recv_into), MP_ROM_PTR(&socketpool_socket_recv_into_obj) }, + { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&socketpool_socket_send_obj) }, + { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socketpool_socket_sendto_obj) }, + { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socketpool_socket_setblocking_obj) }, // { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&socketpool_socket_setsockopt_obj) }, { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&socketpool_socket_settimeout_obj) }, - // { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socketpool_socket_setblocking_obj) }, }; STATIC MP_DEFINE_CONST_DICT(socketpool_socket_locals_dict, socketpool_socket_locals_dict_table); @@ -404,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 b5dceb50f4b45..3e757c73ace94 100644 --- a/shared-bindings/socketpool/Socket.h +++ b/shared-bindings/socketpool/Socket.h @@ -31,22 +31,20 @@ extern const mp_obj_type_t socketpool_socket_type; -void common_hal_socketpool_socket_settimeout(socketpool_socket_obj_t* self, mp_uint_t timeout_ms); - -bool common_hal_socketpool_socket_bind(socketpool_socket_obj_t* self, const char* host, size_t hostlen, uint8_t port); -bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t* self, int backlog); -socketpool_socket_obj_t * common_hal_socketpool_socket_accept(socketpool_socket_obj_t* self, uint8_t* ip, uint *port); - -bool common_hal_socketpool_socket_connect(socketpool_socket_obj_t* self, const char* host, size_t hostlen, mp_int_t port); -mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t* self, const uint8_t* buf, mp_uint_t len); -mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t* self, const uint8_t* buf, mp_uint_t len); -mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t* self, - const char* host, size_t hostlen, uint8_t port, const uint8_t* buf, mp_uint_t len); -mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t* self, - uint8_t* buf, mp_uint_t len, uint8_t* ip, uint *port); -void common_hal_socketpool_socket_close(socketpool_socket_obj_t* self); -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_hash(socketpool_socket_obj_t* self); +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 8f4069faadada..038a0d5337b96 100644 --- a/shared-bindings/socketpool/SocketPool.c +++ b/shared-bindings/socketpool/SocketPool.c @@ -3,8 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2014 Damien P. George - * 2018 Nick Moore for Adafruit Industries + * Copyright (c) 2020 Scott Shawcroft for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -136,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); @@ -159,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 b007aad8f42ce..10a943d38b05e 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 d3f8ba3028aa2..e6f36261aabea 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 9d4df72619d51..4a3dafb9815dc 100644 --- a/shared-bindings/ssl/SSLContext.c +++ b/shared-bindings/ssl/SSLContext.c @@ -51,7 +51,7 @@ STATIC mp_obj_t ssl_sslcontext_make_new(const mp_obj_type_t *type, size_t n_args return MP_OBJ_FROM_PTR(s); } -//| def wrap_socket(sock: socketpool.Socket, *, server_side: bool = False, server_hostname: Optional[str] = None) -> socketpool.Socket: +//| def wrap_socket(sock: socketpool.Socket, *, server_side: bool = False, server_hostname: Optional[str] = None) -> ssl.SSLSocket: //| """Wraps the socket into a socket-compatible class that handles SSL negotiation. //| The socket must be of type SOCK_STREAM.""" //| ... @@ -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 f7f985af70c3c..1e1986a48db97 100644 --- a/shared-bindings/ssl/SSLContext.h +++ b/shared-bindings/ssl/SSLContext.h @@ -30,12 +30,13 @@ #include "common-hal/ssl/SSLContext.h" #include "shared-bindings/socketpool/Socket.h" +#include "shared-bindings/ssl/SSLSocket.h" 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); -socketpool_socket_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 new file mode 100644 index 0000000000000..1c2de28e951c0 --- /dev/null +++ b/shared-bindings/ssl/SSLSocket.c @@ -0,0 +1,326 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Lucian Copeland for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "shared-bindings/ssl/SSLSocket.h" + +#include +#include + +#include "lib/utils/context_manager_helpers.h" +#include "py/objtuple.h" +#include "py/objlist.h" +#include "py/runtime.h" +#include "py/mperrno.h" + +#include "lib/netutils/netutils.h" + +//| class SSLSocket: +//| """Implements TLS security on a subset of `socketpool.Socket` functions. Cannot be created +//| directly. Instead, call `wrap_socket` on an existing socket object. +//| +//| Provides a subset of CPython's `ssl.SSLSocket` API. It only implements the versions of +//| recv that do not allocate bytes objects.""" +//| + +//| def __enter__(self) -> SSLSocket: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically closes the Socket when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_ssl_sslsocket_close(args[0]); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ssl_sslsocket___exit___obj, 4, 4, ssl_sslsocket___exit__); + +//| def accept(self) -> Tuple[SSLSocket, Tuple[str, int]]: +//| """Accept a connection on a listening socket of type SOCK_STREAM, +//| creating a new socket of type SOCK_STREAM. +//| Returns a tuple of (new_socket, remote_address)""" +//| +STATIC mp_obj_t ssl_sslsocket_accept(mp_obj_t self_in) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + uint8_t ip[4]; + uint32_t 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); + tuple_contents[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); + return mp_obj_new_tuple(2, tuple_contents); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(ssl_sslsocket_accept_obj, ssl_sslsocket_accept); + +//| def bind(self, address: Tuple[str, int]) -> None: +//| """Bind a socket to an address +//| +//| :param ~tuple address: tuple of (remote_address, remote_port)""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket_bind(mp_obj_t self_in, mp_obj_t addr_in) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + + mp_obj_t *addr_items; + 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); + mp_int_t port = mp_obj_get_int(addr_items[1]); + if (port < 0) { + mp_raise_ValueError(translate("port must be >= 0")); + } + + bool ok = common_hal_ssl_sslsocket_bind(self, host, hostlen, (uint32_t)port); + if (!ok) { + mp_raise_ValueError(translate("Error: Failure to bind")); + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(ssl_sslsocket_bind_obj, ssl_sslsocket_bind); + +//| def close(self) -> None: +//| """Closes this Socket""" +//| +STATIC mp_obj_t ssl_sslsocket_close(mp_obj_t self_in) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_ssl_sslsocket_close(self); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(ssl_sslsocket_close_obj, ssl_sslsocket_close); + +//| def connect(self, address: Tuple[str, int]) -> None: +//| """Connect a socket to a remote address +//| +//| :param ~tuple address: tuple of (remote_address, remote_port)""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket_connect(mp_obj_t self_in, mp_obj_t addr_in) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + + mp_obj_t *addr_items; + 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); + mp_int_t port = mp_obj_get_int(addr_items[1]); + if (port < 0) { + mp_raise_ValueError(translate("port must be >= 0")); + } + + bool ok = common_hal_ssl_sslsocket_connect(self, host, hostlen, (uint32_t)port); + if (!ok) { + mp_raise_OSError(0); + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(ssl_sslsocket_connect_obj, ssl_sslsocket_connect); + +//| def listen(self, backlog: int) -> None: +//| """Set socket to listen for incoming connections +//| +//| :param ~int backlog: length of backlog queue for waiting connetions""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + + int backlog = mp_obj_get_int(backlog_in); + + common_hal_ssl_sslsocket_listen(self, backlog); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(ssl_sslsocket_listen_obj, ssl_sslsocket_listen); + +//| def recv_into(self, buffer: WriteableBuffer, bufsize: int) -> int: +//| """Reads some bytes from the connected remote address, writing +//| into the provided buffer. If bufsize <= len(buffer) is given, +//| a maximum of bufsize bytes will be read into the buffer. If no +//| valid value is given for bufsize, the default is the length of +//| the given buffer. +//| +//| Suits sockets of type SOCK_STREAM +//| Returns an int of number of bytes read. +//| +//| :param bytearray buffer: buffer to receive into +//| :param int bufsize: optionally, a maximum number of bytes to read.""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket_recv_into(size_t n_args, const mp_obj_t *args) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(args[0]); + if (common_hal_ssl_sslsocket_get_closed(self)) { + // Bad file number. + mp_raise_OSError(MP_EBADF); + } + // if (!common_hal_ssl_sslsocket_get_connected(self)) { + // // not connected + // mp_raise_OSError(MP_ENOTCONN); + // } + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE); + mp_int_t len = bufinfo.len; + if (n_args == 3) { + mp_int_t given_len = mp_obj_get_int(args[2]); + if (given_len > len) { + mp_raise_ValueError(translate("buffer too small for requested bytes")); + } + if (given_len > 0 && given_len < len) { + len = given_len; + } + } + + if (len == 0) { + return MP_OBJ_NEW_SMALL_INT(0); + } + + 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); + +//| def send(self, bytes: ReadableBuffer) -> int: +//| """Send some bytes to the connected remote address. +//| Suits sockets of type SOCK_STREAM +//| +//| :param ~bytes bytes: some bytes to send""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket_send(mp_obj_t self_in, mp_obj_t buf_in) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (common_hal_ssl_sslsocket_get_closed(self)) { + // Bad file number. + mp_raise_OSError(MP_EBADF); + } + if (!common_hal_ssl_sslsocket_get_connected(self)) { + mp_raise_BrokenPipeError(); + } + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); + mp_int_t ret = common_hal_ssl_sslsocket_send(self, bufinfo.buf, bufinfo.len); + if (ret == -1) { + mp_raise_BrokenPipeError(); + } + return mp_obj_new_int_from_uint(ret); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(ssl_sslsocket_send_obj, ssl_sslsocket_send); + +// //| def setsockopt(self, level: int, optname: int, value: int) -> None: +// //| """Sets socket options""" +// //| ... +// //| +// STATIC mp_obj_t ssl_sslsocket_setsockopt(size_t n_args, const mp_obj_t *args) { +// } +// STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ssl_sslsocket_setsockopt_obj, 4, 4, ssl_sslsocket_setsockopt); + +//| def settimeout(self, value: int) -> None: +//| """Set the timeout value for this socket. +//| +//| :param ~int value: timeout in seconds. 0 means non-blocking. None means block indefinitely.""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_uint_t timeout_ms; + if (timeout_in == mp_const_none) { + timeout_ms = -1; + } else { + #if MICROPY_PY_BUILTINS_FLOAT + timeout_ms = 1000 * mp_obj_get_float(timeout_in); + #else + timeout_ms = 1000 * mp_obj_get_int(timeout_in); + #endif + } + common_hal_ssl_sslsocket_settimeout(self, timeout_ms); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(ssl_sslsocket_settimeout_obj, ssl_sslsocket_settimeout); + +//| def setblocking(self, flag: bool) -> Optional[int]: +//| """Set the blocking behaviour of this socket. +//| +//| :param ~bool flag: False means non-blocking, True means block indefinitely.""" +//| ... +//| +// method socket.setblocking(flag) +STATIC mp_obj_t ssl_sslsocket_setblocking(mp_obj_t self_in, mp_obj_t blocking) { + ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (mp_obj_is_true(blocking)) { + common_hal_ssl_sslsocket_settimeout(self, -1); + } else { + common_hal_ssl_sslsocket_settimeout(self, 0); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(ssl_sslsocket_setblocking_obj, ssl_sslsocket_setblocking); + +//| def __hash__(self) -> int: +//| """Returns a hash for the Socket.""" +//| ... +//| +STATIC mp_obj_t ssl_sslsocket_unary_op(mp_unary_op_t op, mp_obj_t self_in) { + switch (op) { + case MP_UNARY_OP_HASH: { + return mp_obj_id(self_in); + } + default: + return MP_OBJ_NULL; // op not supported + } +} + +STATIC const mp_rom_map_elem_t ssl_sslsocket_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&ssl_sslsocket___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&ssl_sslsocket_close_obj) }, + + { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&ssl_sslsocket_accept_obj) }, + { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&ssl_sslsocket_bind_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&ssl_sslsocket_close_obj) }, + { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&ssl_sslsocket_connect_obj) }, + { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&ssl_sslsocket_listen_obj) }, + { MP_ROM_QSTR(MP_QSTR_recv_into), MP_ROM_PTR(&ssl_sslsocket_recv_into_obj) }, + { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&ssl_sslsocket_send_obj) }, + { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&ssl_sslsocket_setblocking_obj) }, + // { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&ssl_sslsocket_setsockopt_obj) }, + { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&ssl_sslsocket_settimeout_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(ssl_sslsocket_locals_dict, ssl_sslsocket_locals_dict_table); + +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, + .unary_op = ssl_sslsocket_unary_op, +}; diff --git a/shared-bindings/ssl/SSLSocket.h b/shared-bindings/ssl/SSLSocket.h new file mode 100644 index 0000000000000..fc6cc8ec141af --- /dev/null +++ b/shared-bindings/ssl/SSLSocket.h @@ -0,0 +1,45 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2020 Lucian Copeland for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_SSL_SSLSOCKET_H +#define MICROPY_INCLUDED_SHARED_BINDINGS_SSL_SSLSOCKET_H + +#include "common-hal/ssl/SSLSocket.h" + +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); + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_SSL_SSLSOCKET_H diff --git a/shared-bindings/ssl/__init__.c b/shared-bindings/ssl/__init__.c index 57f4e6f4afc80..151acfe80ca88 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 5ddada64e6902..64f69c3ed928d 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 cafaf59869049..7b436a4df17b3 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 7851b9e292b3e..eeb0d3a73bb53 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 b886a662e8520..56371d3b9a7ad 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 a7e72b11c7577..4c7c65da38c18 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 8e0259a3b38f4..9e97407f6e721 --- a/shared-bindings/supervisor/Runtime.c +++ b/shared-bindings/supervisor/Runtime.c @@ -33,9 +33,12 @@ #include "shared-bindings/supervisor/RunReason.h" #include "shared-bindings/supervisor/Runtime.h" +#include "tusb.h" + STATIC supervisor_run_reason_t _run_reason; -//TODO: add USB, REPL to description once they're operational +// TODO: add REPL to description once it is operational + //| class Runtime: //| """Current status of runtime objects. //| @@ -52,62 +55,68 @@ STATIC supervisor_run_reason_t _run_reason; //| ... //| +//| usb_connected: bool +//| """Returns the USB enumeration status (read-only).""" +//| +STATIC mp_obj_t supervisor_runtime_get_usb_connected(mp_obj_t self) { + #if CIRCUITPY_USB + return mp_obj_new_bool(tud_ready()); + #else + return mp_const_false; + #endif +} +MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_usb_connected_obj, supervisor_runtime_get_usb_connected); + +const mp_obj_property_t supervisor_runtime_usb_connected_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&supervisor_runtime_get_usb_connected_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + //| serial_connected: bool //| """Returns the USB serial communication status (read-only).""" //| - -STATIC mp_obj_t supervisor_get_serial_connected(mp_obj_t self){ - if (!common_hal_get_serial_connected()) { - return mp_const_false; - } - else { - return mp_const_true; - } +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_get_serial_connected_obj, supervisor_get_serial_connected); +MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_serial_connected_obj, supervisor_runtime_get_serial_connected); -const mp_obj_property_t supervisor_serial_connected_obj = { +const mp_obj_property_t supervisor_runtime_serial_connected_obj = { .base.type = &mp_type_property, - .proxy = {(mp_obj_t)&supervisor_get_serial_connected_obj, + .proxy = {(mp_obj_t)&supervisor_runtime_get_serial_connected_obj, (mp_obj_t)&mp_const_none_obj, (mp_obj_t)&mp_const_none_obj}, }; - //| serial_bytes_available: int //| """Returns the whether any bytes are available to read //| 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_get_serial_bytes_available(mp_obj_t self){ - if (!common_hal_get_serial_bytes_available()) { - return mp_const_false; - } - else { - return mp_const_true; - } +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_get_serial_bytes_available_obj, supervisor_get_serial_bytes_available); +MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_serial_bytes_available_obj, supervisor_runtime_get_serial_bytes_available); -const mp_obj_property_t supervisor_serial_bytes_available_obj = { +const mp_obj_property_t supervisor_runtime_serial_bytes_available_obj = { .base.type = &mp_type_property, - .proxy = {(mp_obj_t)&supervisor_get_serial_bytes_available_obj, + .proxy = {(mp_obj_t)&supervisor_runtime_get_serial_bytes_available_obj, (mp_obj_t)&mp_const_none_obj, (mp_obj_t)&mp_const_none_obj}, }; - //| run_reason: RunReason //| """Returns why CircuitPython started running this particular time.""" //| -STATIC mp_obj_t supervisor_get_run_reason(mp_obj_t self) { +STATIC mp_obj_t supervisor_runtime_get_run_reason(mp_obj_t self) { return cp_enum_find(&supervisor_run_reason_type, _run_reason); } -MP_DEFINE_CONST_FUN_OBJ_1(supervisor_get_run_reason_obj, supervisor_get_run_reason); +MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_run_reason_obj, supervisor_runtime_get_run_reason); -const mp_obj_property_t supervisor_run_reason_obj = { +const mp_obj_property_t supervisor_runtime_run_reason_obj = { .base.type = &mp_type_property, - .proxy = {(mp_obj_t)&supervisor_get_run_reason_obj, + .proxy = {(mp_obj_t)&supervisor_runtime_get_run_reason_obj, (mp_obj_t)&mp_const_none_obj, (mp_obj_t)&mp_const_none_obj}, }; @@ -117,9 +126,10 @@ void supervisor_set_run_reason(supervisor_run_reason_t run_reason) { } STATIC const mp_rom_map_elem_t supervisor_runtime_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_serial_connected), MP_ROM_PTR(&supervisor_serial_connected_obj) }, - { MP_ROM_QSTR(MP_QSTR_serial_bytes_available), MP_ROM_PTR(&supervisor_serial_bytes_available_obj) }, - { MP_ROM_QSTR(MP_QSTR_run_reason), MP_ROM_PTR(&supervisor_run_reason_obj) }, + { MP_ROM_QSTR(MP_QSTR_usb_connected), MP_ROM_PTR(&supervisor_runtime_usb_connected_obj) }, + { MP_ROM_QSTR(MP_QSTR_serial_connected), MP_ROM_PTR(&supervisor_runtime_serial_connected_obj) }, + { MP_ROM_QSTR(MP_QSTR_serial_bytes_available), MP_ROM_PTR(&supervisor_runtime_serial_bytes_available_obj) }, + { MP_ROM_QSTR(MP_QSTR_run_reason), MP_ROM_PTR(&supervisor_runtime_run_reason_obj) }, }; STATIC MP_DEFINE_CONST_DICT(supervisor_runtime_locals_dict, supervisor_runtime_locals_dict_table); diff --git a/shared-bindings/supervisor/Runtime.h b/shared-bindings/supervisor/Runtime.h old mode 100755 new mode 100644 index 51ed7604df7b8..3a94a8fd5d3ce --- a/shared-bindings/supervisor/Runtime.h +++ b/shared-bindings/supervisor/Runtime.h @@ -36,12 +36,12 @@ extern const mp_obj_type_t supervisor_runtime_type; void supervisor_set_run_reason(supervisor_run_reason_t run_reason); -bool common_hal_get_serial_connected(void); +bool common_hal_supervisor_runtime_get_serial_connected(void); -bool common_hal_get_serial_bytes_available(void); +bool common_hal_supervisor_runtime_get_serial_bytes_available(void); -//TODO: placeholders for future functions -//bool common_hal_get_repl_active(void); -//bool common_hal_get_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 ad86030478302..28ac68d629ea4 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 b79bdacca31cf..a2ad3dd6d4861 --- 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/support_matrix.rst b/shared-bindings/support_matrix.rst index a2fb7987d28d8..2d2172122abd6 100644 --- a/shared-bindings/support_matrix.rst +++ b/shared-bindings/support_matrix.rst @@ -6,6 +6,11 @@ Module Support Matrix - Which Modules Are Available on Which Boards The following table lists the available built-in modules for each CircuitPython capable board. +.. raw:: html + +

(all)

+ +.. rst-class:: support-matrix-table .. list-table:: :header-rows: 1 :widths: 7, 50 diff --git a/shared-bindings/synthio/MidiTrack.c b/shared-bindings/synthio/MidiTrack.c new file mode 100644 index 0000000000000..65fc7a4ee1745 --- /dev/null +++ b/shared-bindings/synthio/MidiTrack.c @@ -0,0 +1,169 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "lib/utils/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-bindings/synthio/MidiTrack.h" +#include "supervisor/shared/translate.h" + +//| class MidiTrack: +//| """Simple square-wave MIDI synth""" +//| +//| def __init__(self, buffer: ReadableBuffer, tempo: int, *, sample_rate: int = 11025) -> None: +//| """Create a MidiTrack from the given stream of MIDI events. Only "Note On" and "Note Off" events +//| are supported; channel numbers and key velocities are ignored. Up to two notes may be on at the +//| same time. +//| +//| :param ~_typing.ReadableBuffer buffer: Stream of MIDI events, as stored in a MIDI file track chunk +//| :param int tempo: Tempo of the streamed events, in MIDI ticks per second +//| :param int sample_rate: The desired playback sample rate; higher sample rate requires more memory +//| +//| Simple melody:: +//| +//| import audioio +//| import board +//| import synthio +//| +//| dac = audioio.AudioOut(board.SPEAKER) +//| melody = synthio.MidiTrack(b"\\0\\x90H\\0*\\x80H\\0\\6\\x90J\\0*\\x80J\\0\\6\\x90L\\0*\\x80L\\0\\6\\x90J\\0" + +//| b"*\\x80J\\0\\6\\x90H\\0*\\x80H\\0\\6\\x90J\\0*\\x80J\\0\\6\\x90L\\0T\\x80L\\0" + +//| b"\\x0c\\x90H\\0T\\x80H\\0\\x0c\\x90H\\0T\\x80H\\0", tempo=640) +//| dac.play(melody) +//| print("playing") +//| while dac.playing: +//| pass +//| print("stopped")""" +//| ... +//| +STATIC mp_obj_t synthio_miditrack_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_buffer, ARG_tempo, ARG_sample_rate }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_buffer, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_tempo, MP_ARG_INT | MP_ARG_REQUIRED }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 11025} }, + }; + 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_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); + + synthio_miditrack_obj_t *self = m_new_obj(synthio_miditrack_obj_t); + self->base.type = &synthio_miditrack_type; + + common_hal_synthio_miditrack_construct(self, + (uint8_t *)bufinfo.buf, bufinfo.len, + args[ARG_tempo].u_int, + args[ARG_sample_rate].u_int); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the MidiTrack and releases any hardware resources for reuse.""" +//| ... +//| +STATIC mp_obj_t synthio_miditrack_deinit(mp_obj_t self_in) { + synthio_miditrack_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_synthio_miditrack_deinit(self); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(synthio_miditrack_deinit_obj, synthio_miditrack_deinit); + +STATIC void check_for_deinit(synthio_miditrack_obj_t *self) { + if (common_hal_synthio_miditrack_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> MidiTrack: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes the hardware when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +STATIC mp_obj_t synthio_miditrack_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_synthio_miditrack_deinit(args[0]); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(synthio_miditrack___exit___obj, 4, 4, synthio_miditrack_obj___exit__); + +//| sample_rate: Optional[int] +//| """32 bit value that tells how quickly samples are played in Hertz (cycles per second).""" +//| +STATIC mp_obj_t synthio_miditrack_obj_get_sample_rate(mp_obj_t self_in) { + synthio_miditrack_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_synthio_miditrack_get_sample_rate(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(synthio_miditrack_get_sample_rate_obj, synthio_miditrack_obj_get_sample_rate); + +const mp_obj_property_t synthio_miditrack_sample_rate_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&synthio_miditrack_get_sample_rate_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +STATIC const mp_rom_map_elem_t synthio_miditrack_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&synthio_miditrack_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&synthio_miditrack___exit___obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_sample_rate), MP_ROM_PTR(&synthio_miditrack_sample_rate_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(synthio_miditrack_locals_dict, synthio_miditrack_locals_dict_table); + +STATIC const audiosample_p_t synthio_miditrack_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .sample_rate = (audiosample_sample_rate_fun)common_hal_synthio_miditrack_get_sample_rate, + .bits_per_sample = (audiosample_bits_per_sample_fun)common_hal_synthio_miditrack_get_bits_per_sample, + .channel_count = (audiosample_channel_count_fun)common_hal_synthio_miditrack_get_channel_count, + .reset_buffer = (audiosample_reset_buffer_fun)synthio_miditrack_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)synthio_miditrack_get_buffer, + .get_buffer_structure = (audiosample_get_buffer_structure_fun)synthio_miditrack_get_buffer_structure, +}; + +const mp_obj_type_t synthio_miditrack_type = { + { &mp_type_type }, + .name = MP_QSTR_MidiTrack, + .make_new = synthio_miditrack_make_new, + .locals_dict = (mp_obj_dict_t *)&synthio_miditrack_locals_dict, + .protocol = &synthio_miditrack_proto, +}; diff --git a/shared-bindings/synthio/MidiTrack.h b/shared-bindings/synthio/MidiTrack.h new file mode 100644 index 0000000000000..d44d4c3bb7bda --- /dev/null +++ b/shared-bindings/synthio/MidiTrack.h @@ -0,0 +1,43 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO_MIDITRACK_H +#define MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO_MIDITRACK_H + +#include "shared-module/synthio/MidiTrack.h" + +extern const mp_obj_type_t synthio_miditrack_type; + +void common_hal_synthio_miditrack_construct(synthio_miditrack_obj_t *self, + const uint8_t *buffer, uint32_t len, uint32_t tempo, uint32_t sample_rate); + +void common_hal_synthio_miditrack_deinit(synthio_miditrack_obj_t *self); +bool common_hal_synthio_miditrack_deinited(synthio_miditrack_obj_t *self); +uint32_t common_hal_synthio_miditrack_get_sample_rate(synthio_miditrack_obj_t *self); +uint8_t common_hal_synthio_miditrack_get_bits_per_sample(synthio_miditrack_obj_t *self); +uint8_t common_hal_synthio_miditrack_get_channel_count(synthio_miditrack_obj_t *self); + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO_MIDITRACK_H diff --git a/shared-bindings/synthio/__init__.c b/shared-bindings/synthio/__init__.c new file mode 100644 index 0000000000000..d5165001fc3d1 --- /dev/null +++ b/shared-bindings/synthio/__init__.c @@ -0,0 +1,136 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/mperrno.h" +#include "py/obj.h" +#include "py/runtime.h" +#include "extmod/vfs_fat.h" + +#include "shared-bindings/synthio/__init__.h" +#include "shared-bindings/synthio/MidiTrack.h" + +//| """Support for MIDI synthesis""" +//| +//| def from_file(file: typing.BinaryIO, *, sample_rate: int = 11025) -> MidiTrack: +//| """Create an AudioSample from an already opened MIDI file. +//| Currently, only single-track MIDI (type 0) is supported. +//| +//| :param typing.BinaryIO file: Already opened MIDI file +//| :param int sample_rate: The desired playback sample rate; higher sample rate requires more memory +//| +//| +//| Playing a MIDI file from flash:: +//| +//| import audioio +//| import board +//| import synthio +//| +//| data = open("single-track.midi", "rb") +//| midi = synthio.from_file(data) +//| a = audioio.AudioOut(board.A0) +//| +//| print("playing") +//| a.play(midi) +//| while a.playing: +//| pass +//| print("stopped")""" +//| ... +//| +STATIC mp_obj_t synthio_from_file(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_file, ARG_sample_rate }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 11025} }, + }; + 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); + if (!MP_OBJ_IS_TYPE(args[ARG_file].u_obj, &mp_type_fileio)) { + mp_raise_TypeError(translate("file must be a file opened in byte mode")); + } + pyb_file_obj_t *file = MP_OBJ_TO_PTR(args[ARG_file].u_obj); + + uint8_t chunk_header[14]; + f_rewind(&file->fp); + UINT bytes_read; + if (f_read(&file->fp, chunk_header, sizeof(chunk_header), &bytes_read) != FR_OK) { + mp_raise_OSError(MP_EIO); + } + if (bytes_read != sizeof(chunk_header) || + memcmp(chunk_header, "MThd\0\0\0\6\0\0\0\1", 12)) { + mp_raise_ValueError(translate("Invalid MIDI file")); + // TODO: for a multi-track MIDI (type 1), return an AudioMixer + } + + uint16_t tempo; + if (chunk_header[12] & 0x80) { + tempo = -(int8_t)chunk_header[12] * chunk_header[13]; + } else { + tempo = 2 * ((chunk_header[12] << 8) | chunk_header[13]); + } + + if (f_read(&file->fp, chunk_header, 8, &bytes_read) != FR_OK) { + mp_raise_OSError(MP_EIO); + } + if (bytes_read != 8 || memcmp(chunk_header, "MTrk", 4)) { + mp_raise_ValueError(translate("Invalid MIDI file")); + } + uint32_t track_size = (chunk_header[4] << 24) | + (chunk_header[5] << 16) | (chunk_header[6] << 8) | chunk_header[7]; + uint8_t *buffer = m_malloc(track_size, false); + if (f_read(&file->fp, buffer, track_size, &bytes_read) != FR_OK) { + mp_raise_OSError(MP_EIO); + } + if (bytes_read != track_size) { + mp_raise_ValueError(translate("Invalid MIDI file")); + } + + synthio_miditrack_obj_t *result = m_new_obj(synthio_miditrack_obj_t); + result->base.type = &synthio_miditrack_type; + + common_hal_synthio_miditrack_construct(result, buffer, track_size, + tempo, args[ARG_sample_rate].u_int); + + m_free(buffer); + + return MP_OBJ_FROM_PTR(result); +} +MP_DEFINE_CONST_FUN_OBJ_KW(synthio_from_file_obj, 1, synthio_from_file); + + +STATIC const mp_rom_map_elem_t synthio_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_synthio) }, + { MP_ROM_QSTR(MP_QSTR_MidiTrack), MP_ROM_PTR(&synthio_miditrack_type) }, + { MP_ROM_QSTR(MP_QSTR_from_file), MP_ROM_PTR(&synthio_from_file_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(synthio_module_globals, synthio_module_globals_table); + +const mp_obj_module_t synthio_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&synthio_module_globals, +}; diff --git a/shared-bindings/synthio/__init__.h b/shared-bindings/synthio/__init__.h new file mode 100644 index 0000000000000..14af1a5805ebc --- /dev/null +++ b/shared-bindings/synthio/__init__.h @@ -0,0 +1,34 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO___INIT___H +#define MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO___INIT___H + +#include "py/obj.h" + +// Nothing now. + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_SYNTHIO___INIT___H diff --git a/shared-bindings/terminalio/Terminal.c b/shared-bindings/terminalio/Terminal.c index 3d53e3cce7543..b1d3cce6537cd 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 7ae0bf1b032f7..f884edd6d57ca 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 9cd1da5b67a81..084b76f21e898 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 2624384afbcf9..87f766db260af 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); @@ -279,7 +279,7 @@ STATIC mp_obj_t time_mktime(mp_obj_t t) { mp_obj_tuple_get(t, &len, &elem); if (len != 9) { - mp_raise_TypeError_varg(translate("function takes %d positional arguments but %d were given"), 9); + mp_raise_TypeError_varg(translate("function takes %d positional arguments but %d were given"), 9, len); } if (mp_obj_get_int(elem[0]) < 2000) { @@ -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 ff723ccc7444c..8fb36eab45ff3 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] @@ -153,7 +153,13 @@ const mp_obj_property_t touchio_touchin_raw_value_obj = { //| When the **TouchIn** object is created, an initial `raw_value` is read from the pin, //| and then `threshold` is set to be 100 + that value. //| -//| You can adjust `threshold` to make the pin more or less sensitive.""" +//| You can adjust `threshold` to make the pin more or less sensitive:: +//| +//| import board +//| import touchio +//| +//| touch = touchio.TouchIn(board.A1) +//| touch.threshold = 7300""" //| STATIC mp_obj_t touchio_touchin_obj_get_threshold(mp_obj_t self_in) { touchio_touchin_obj_t *self = MP_OBJ_TO_PTR(self_in); diff --git a/shared-bindings/touchio/TouchIn.h b/shared-bindings/touchio/TouchIn.h index 42f9da46d5856..1da2cf190a5a8 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 92e067cf68705..3c3413438e787 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 daf55a6138f44..8c9e2e81dc257 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 new file mode 100644 index 0000000000000..ab05494519603 --- /dev/null +++ b/shared-bindings/usb_cdc/Serial.c @@ -0,0 +1,318 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dan Halbert for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "shared-bindings/usb_cdc/Serial.h" +#include "shared-bindings/util.h" + +#include "py/ioctl.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "py/stream.h" +#include "supervisor/shared/translate.h" + +//| class Serial: +//| """Receives cdc commands over USB""" +//| +//| def __init__(self) -> None: +//| """You cannot create an instance of `usb_cdc.Serial`. +//| The available instances are in the ``usb_cdc.serials`` tuple.""" +//| ... +//| +//| def read(self, size: int = 1) -> bytes: +//| """Read at most ``size`` bytes. If ``size`` exceeds the internal buffer size +//| only the bytes in the buffer will be read. If `timeout` is > 0 or ``None``, +//| and fewer than ``size`` bytes are available, keep waiting until the timeout +//| expires or ``size`` bytes are available. +//| +//| :return: Data read +//| :rtype: bytes""" +//| ... +//| +//| def readinto(self, buf: WriteableBuffer) -> int: +//| """Read bytes into the ``buf``. If ``nbytes`` is specified then read at most +//| that many bytes, subject to `timeout`. Otherwise, read at most ``len(buf)`` bytes. +//| +//| :return: number of bytes read and stored into ``buf`` +//| :rtype: bytes""" +//| ... +//| +//| def readline(self, size: int = -1) -> Optional[bytes]: +//| r"""Read a line ending in a newline character ("\\n"), including the newline. +//| Return everything readable if no newline is found and ``timeout`` is 0. +//| Return ``None`` in case of error. +//| +//| This is a binary stream: the newline character "\\n" cannot be changed. +//| If the host computer transmits "\\r" it will also be included as part of the line. +//| +//| :param int size: maximum number of characters to read. ``-1`` means as many as possible. +//| :return: the line read +//| :rtype: bytes or None""" +//| ... +//| +//| def readlines(self) -> List[Optional[bytes]]: +//| """Read multiple lines as a list, using `readline()`. +//| +//| .. warning:: If ``timeout`` is ``None``, +//| `readlines()` will never return, because there is no way to indicate end of stream. +//| +//| :return: a list of the line read +//| :rtype: list""" +//| ... +//| +//| def write(self, buf: ReadableBuffer) -> int: +//| """Write as many bytes as possible from the buffer of bytes. +//| +//| :return: the number of bytes written +//| :rtype: int""" +//| ... +//| +//| def flush(self) -> None: +//| """Force out any unwritten bytes, waiting until they are written.""" +//| ... +//| + +// These three methods are used by the shared stream methods. +STATIC mp_uint_t usb_cdc_serial_read_stream(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + byte *buf = buf_in; + + // make sure we want at least 1 char + if (size == 0) { + return 0; + } + + return common_hal_usb_cdc_serial_read(self, buf, size, errcode); +} + +STATIC mp_uint_t usb_cdc_serial_write_stream(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + const byte *buf = buf_in; + + return common_hal_usb_cdc_serial_write(self, buf, size, errcode); +} + +STATIC mp_uint_t usb_cdc_serial_ioctl_stream(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_uint_t ret = 0; + switch (request) { + case MP_IOCTL_POLL: { + mp_uint_t flags = arg; + ret = 0; + if ((flags & MP_IOCTL_POLL_RD) && common_hal_usb_cdc_serial_get_in_waiting(self) > 0) { + ret |= MP_IOCTL_POLL_RD; + } + if ((flags & MP_IOCTL_POLL_WR) && common_hal_usb_cdc_serial_get_out_waiting(self) == 0) { + ret |= MP_IOCTL_POLL_WR; + } + break; + } + + case MP_STREAM_FLUSH: + common_hal_usb_cdc_serial_flush(self); + break; + + default: + *errcode = MP_EINVAL; + ret = MP_STREAM_ERROR; + } + return ret; +} + +//| connected: bool +//| """True if this Serial is connected to a host. (read-only) +//| +//| .. note:: The host is considered to be connected if it is asserting DTR (Data Terminal Ready). +//| Most terminal programs and ``pyserial`` assert DTR when opening a serial connection. +//| However, the C# ``SerialPort`` API does not. You must set ``SerialPort.DtrEnable``. +//| """ +//| +STATIC mp_obj_t usb_cdc_serial_get_connected(mp_obj_t self_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bool(common_hal_usb_cdc_serial_get_connected(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_get_connected_obj, usb_cdc_serial_get_connected); + +const mp_obj_property_t usb_cdc_serial_connected_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&usb_cdc_serial_get_connected_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +//| in_waiting: int +//| """Returns the number of bytes waiting to be read on the USB serial input. (read-only)""" +//| +STATIC mp_obj_t usb_cdc_serial_get_in_waiting(mp_obj_t self_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_int(common_hal_usb_cdc_serial_get_in_waiting(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_get_in_waiting_obj, usb_cdc_serial_get_in_waiting); + +const mp_obj_property_t usb_cdc_serial_in_waiting_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&usb_cdc_serial_get_in_waiting_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +//| out_waiting: int +//| """Returns the number of bytes waiting to be written on the USB serial output. (read-only)""" +//| +STATIC mp_obj_t usb_cdc_serial_get_out_waiting(mp_obj_t self_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_int(common_hal_usb_cdc_serial_get_out_waiting(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_get_out_waiting_obj, usb_cdc_serial_get_out_waiting); + +const mp_obj_property_t usb_cdc_serial_out_waiting_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&usb_cdc_serial_get_out_waiting_obj, + (mp_obj_t)&mp_const_none_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +//| def reset_input_buffer(self) -> None: +//| """Clears any unread bytes.""" +//| ... +//| +STATIC mp_obj_t usb_cdc_serial_reset_input_buffer(mp_obj_t self_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_cdc_serial_reset_input_buffer(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_reset_input_buffer_obj, usb_cdc_serial_reset_input_buffer); + +//| def reset_output_buffer(self) -> None: +//| """Clears any unwritten bytes.""" +//| ... +//| +STATIC mp_obj_t usb_cdc_serial_reset_output_buffer(mp_obj_t self_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_cdc_serial_reset_output_buffer(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_reset_output_buffer_obj, usb_cdc_serial_reset_output_buffer); + +//| timeout: Optional[float] +//| """The initial value of `timeout` is ``None``. If ``None``, wait indefinitely to satisfy +//| the conditions of a read operation. If 0, do not wait. If > 0, wait only ``timeout`` seconds.""" +//| +STATIC mp_obj_t usb_cdc_serial_get_timeout(mp_obj_t self_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_float_t timeout = common_hal_usb_cdc_serial_get_timeout(self); + return (timeout < 0.0f) ? mp_const_none : mp_obj_new_float(self->timeout); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_get_timeout_obj, usb_cdc_serial_get_timeout); + +STATIC mp_obj_t usb_cdc_serial_set_timeout(mp_obj_t self_in, mp_obj_t timeout_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_cdc_serial_set_timeout(self, + timeout_in == mp_const_none ? -1.0f : mp_obj_get_float(timeout_in)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(usb_cdc_serial_set_timeout_obj, usb_cdc_serial_set_timeout); + +const mp_obj_property_t usb_cdc_serial_timeout_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&usb_cdc_serial_get_timeout_obj, + (mp_obj_t)&usb_cdc_serial_set_timeout_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + +//| write_timeout: Optional[float] +//| """The initial value of `write_timeout` is ``None``. If ``None``, wait indefinitely to finish +//| writing all the bytes passed to ``write()``.If 0, do not wait. +//| If > 0, wait only ``write_timeout`` seconds.""" +//| +STATIC mp_obj_t usb_cdc_serial_get_write_timeout(mp_obj_t self_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_float_t write_timeout = common_hal_usb_cdc_serial_get_write_timeout(self); + return (write_timeout < 0.0f) ? mp_const_none : mp_obj_new_float(self->write_timeout); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_get_write_timeout_obj, usb_cdc_serial_get_write_timeout); + +STATIC mp_obj_t usb_cdc_serial_set_write_timeout(mp_obj_t self_in, mp_obj_t write_timeout_in) { + usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_cdc_serial_set_write_timeout(self, + write_timeout_in == mp_const_none ? -1.0f : mp_obj_get_float(write_timeout_in)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(usb_cdc_serial_set_write_timeout_obj, usb_cdc_serial_set_write_timeout); + +const mp_obj_property_t usb_cdc_serial_write_timeout_obj = { + .base.type = &mp_type_property, + .proxy = {(mp_obj_t)&usb_cdc_serial_get_write_timeout_obj, + (mp_obj_t)&usb_cdc_serial_set_write_timeout_obj, + (mp_obj_t)&mp_const_none_obj}, +}; + + +STATIC const mp_rom_map_elem_t usb_cdc_serial_locals_dict_table[] = { + // Standard stream methods. + { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, + { MP_OBJ_NEW_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)}, + { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj)}, + { MP_OBJ_NEW_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, + + // Other pyserial-inspired attributes. + { MP_OBJ_NEW_QSTR(MP_QSTR_in_waiting), MP_ROM_PTR(&usb_cdc_serial_in_waiting_obj) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_out_waiting), MP_ROM_PTR(&usb_cdc_serial_out_waiting_obj) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_reset_input_buffer), MP_ROM_PTR(&usb_cdc_serial_reset_input_buffer_obj) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_reset_output_buffer), MP_ROM_PTR(&usb_cdc_serial_reset_output_buffer_obj) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_timeout), MP_ROM_PTR(&usb_cdc_serial_timeout_obj) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_write_timeout), MP_ROM_PTR(&usb_cdc_serial_write_timeout_obj) }, + + // Not in pyserial protocol. + { MP_OBJ_NEW_QSTR(MP_QSTR_connected), MP_ROM_PTR(&usb_cdc_serial_connected_obj) }, + + + +}; +STATIC MP_DEFINE_CONST_DICT(usb_cdc_serial_locals_dict, usb_cdc_serial_locals_dict_table); + +STATIC const mp_stream_p_t usb_cdc_serial_stream_p = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_stream) + .read = usb_cdc_serial_read_stream, + .write = usb_cdc_serial_write_stream, + .ioctl = usb_cdc_serial_ioctl_stream, + .is_text = false, + .pyserial_read_compatibility = true, + .pyserial_readinto_compatibility = true, + .pyserial_dont_return_none_compatibility = true, +}; + +const mp_obj_type_t usb_cdc_serial_type = { + { &mp_type_type }, + .name = MP_QSTR_Serial, + .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, +}; diff --git a/shared-bindings/usb_cdc/Serial.h b/shared-bindings/usb_cdc/Serial.h new file mode 100644 index 0000000000000..cdf5c3a914acd --- /dev/null +++ b/shared-bindings/usb_cdc/Serial.h @@ -0,0 +1,53 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dan Halbert for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_USB_CDC_SERIAL_H +#define MICROPY_INCLUDED_SHARED_BINDINGS_USB_CDC_SERIAL_H + +#include "shared-module/usb_cdc/Serial.h" + +extern const mp_obj_type_t usb_cdc_serial_type; + +extern size_t common_hal_usb_cdc_serial_read(usb_cdc_serial_obj_t *self, uint8_t *data, size_t len, int *errcode); +extern size_t common_hal_usb_cdc_serial_write(usb_cdc_serial_obj_t *self, const uint8_t *data, size_t len, int *errcode); + +extern uint32_t common_hal_usb_cdc_serial_get_in_waiting(usb_cdc_serial_obj_t *self); +extern uint32_t common_hal_usb_cdc_serial_get_out_waiting(usb_cdc_serial_obj_t *self); + +extern void common_hal_usb_cdc_serial_reset_input_buffer(usb_cdc_serial_obj_t *self); +extern uint32_t common_hal_usb_cdc_serial_reset_output_buffer(usb_cdc_serial_obj_t *self); + +extern uint32_t common_hal_usb_cdc_serial_flush(usb_cdc_serial_obj_t *self); + +extern bool common_hal_usb_cdc_serial_get_connected(usb_cdc_serial_obj_t *self); + +extern mp_float_t common_hal_usb_cdc_serial_get_timeout(usb_cdc_serial_obj_t *self); +extern void common_hal_usb_cdc_serial_set_timeout(usb_cdc_serial_obj_t *self, mp_float_t timeout); + +extern mp_float_t common_hal_usb_cdc_serial_get_write_timeout(usb_cdc_serial_obj_t *self); +extern void common_hal_usb_cdc_serial_set_write_timeout(usb_cdc_serial_obj_t *self, mp_float_t write_timeout); + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_USB_CDC_SERIAL_H diff --git a/shared-bindings/usb_cdc/__init__.c b/shared-bindings/usb_cdc/__init__.c new file mode 100644 index 0000000000000..9e9ccb898dd2b --- /dev/null +++ b/shared-bindings/usb_cdc/__init__.c @@ -0,0 +1,59 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dan Halbertfor Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/usb_cdc/__init__.h" +#include "shared-bindings/usb_cdc/Serial.h" + +#include "py/runtime.h" + +//| """USB CDC Serial streams +//| +//| The `usb_cdc` module allows access to USB CDC (serial) communications.""" +//| +//| serials: Tuple[Serial, ...] +//| """Tuple of all CDC streams. Each item is a `Serial`. +//| ``serials[0]`` is the USB REPL connection. +//| ``serials[1]`` is a second USB serial connection, unconnected to the REPL. +//| """ +//| + +static const mp_map_elem_t usb_cdc_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usb_cdc) }, + { MP_ROM_QSTR(MP_QSTR_Serial), MP_OBJ_FROM_PTR(&usb_cdc_serial_type) }, + { MP_ROM_QSTR(MP_QSTR_serials), MP_OBJ_FROM_PTR(&usb_cdc_serials_tuple) }, +}; + +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, +}; diff --git a/shared-bindings/usb_cdc/__init__.h b/shared-bindings/usb_cdc/__init__.h new file mode 100644 index 0000000000000..e81d243e6ccd8 --- /dev/null +++ b/shared-bindings/usb_cdc/__init__.h @@ -0,0 +1,32 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dan Halbert for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_USB_CDC___INIT___H +#define MICROPY_INCLUDED_SHARED_BINDINGS_USB_CDC___INIT___H + +#include "shared-module/usb_cdc/__init__.h" + +#endif // MICROPY_INCLUDED_SHARED_BINDINGS_USB_CDC___INIT___H diff --git a/shared-bindings/usb_hid/Device.c b/shared-bindings/usb_hid/Device.c index c7c05a9749bd3..cd4f3dd54b2b7 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 017995ccc3ecc..d9918d40600b3 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 36111e9194629..1a2f28d4312c6 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 c621c8c502113..735d9da18ad86 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 ce7062ed3c2ce..42fb61016e301 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 1eac2fa985dcb..7d8a014dad475 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 d88a0db48d826..4bbe46fda5798 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 de48c838a2176..e2a31e9c473e9 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 8f0d58d873550..f7cf254fa47c2 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 6a72f912463bb..737476c5ef5d8 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 9a637f317c39d..a50a8a14b3b60 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 bc8c8d29c72d8..7c7f467b092ad 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 d098504e93749..fa11f73ffd12a 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 c7478342636ae..12fb4d72b156c 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 71512bdf8d5f1..513884cdfc933 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 575021a2191ed..a27d26c20cba5 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 76e6317294044..0911aca282d96 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 8181fc4c968d2..5c7fe14924e12 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 64c1052f7b052..333c82bab5c8e 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 352ceb33181bc..38bd1bf07869d 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 8df06b5467687..68402fd105368 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 5e9a3a9fbca96..9ee1c6d58c0e5 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 7776b1fa5744c..298592b9ebe8c 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 af9e4b3471854..28ff215a35860 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 94361a397dd7e..9e142fd6e0bbb 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 cb48d636dcc73..25ce387d07d91 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 8912357a977e0..fa181aabee0e9 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 579729d42c9d9..0df77b65cbde2 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 f3e679631e6d6..df160b1ffa0e5 100644 --- a/shared-module/_pixelbuf/PixelBuf.c +++ b/shared-module/_pixelbuf/PixelBuf.c @@ -31,17 +31,18 @@ #include "py/runtime.h" #include "shared-bindings/_pixelbuf/PixelBuf.h" #include +#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 @@ -55,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; @@ -69,6 +70,7 @@ void common_hal__pixelbuf_pixelbuf_construct(pixelbuf_pixelbuf_obj_t *self, size } // Call set_brightness so that it can allocate a second buffer if needed. self->brightness = 1.0; + self->scaled_brightness = 0x100; common_hal__pixelbuf_pixelbuf_set_brightness(MP_OBJ_FROM_PTR(self), brightness); // Turn on auto_write. We don't want to do it with the above brightness call. @@ -76,59 +78,65 @@ 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. - mp_float_t change = brightness - self->brightness; - if (-0.001 < change && change < 0.001) { + self->brightness = brightness; + // Use 256 steps of brightness so that we can do integer math below. + uint16_t new_scaled_brightness = (uint16_t)(brightness * 256); + if (new_scaled_brightness == self->scaled_brightness) { return; } - self->brightness = brightness; + self->scaled_brightness = new_scaled_brightness; size_t pixel_len = self->pixel_count * self->bytes_per_pixel; - if (self->pre_brightness_buffer == NULL) { - self->pre_brightness_buffer = m_malloc(pixel_len, false); - memcpy(self->pre_brightness_buffer, self->post_brightness_buffer, pixel_len); - } - for (size_t i = 0; i < pixel_len; i++) { - // Don't adjust per-pixel luminance bytes in dotstar mode - if (self->byteorder.is_dotstar && i % 4 == 0) { - continue; + if (self->scaled_brightness == 0x100 && !self->pre_brightness_buffer) { + return; + } else { + if (self->pre_brightness_buffer == NULL) { + self->pre_brightness_buffer = m_malloc(pixel_len, false); + memcpy(self->pre_brightness_buffer, self->post_brightness_buffer, pixel_len); + } + for (size_t i = 0; i < pixel_len; i++) { + // Don't adjust per-pixel luminance bytes in dotstar mode + if (self->byteorder.is_dotstar && i % 4 == 0) { + continue; + } + self->post_brightness_buffer[i] = (self->pre_brightness_buffer[i] * self->scaled_brightness) / 256; } - self->post_brightness_buffer[i] = self->pre_brightness_buffer[i] * self->brightness; - } - if (self->auto_write) { - common_hal__pixelbuf_pixelbuf_show(self_in); + if (self->auto_write) { + common_hal__pixelbuf_pixelbuf_show(self_in); + } } } @@ -141,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. @@ -189,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) { @@ -197,31 +205,37 @@ void _pixelbuf_set_pixel_color(pixelbuf_pixelbuf_obj_t* self, size_t index, uint } pixelbuf_rgbw_t *rgbw_order = &self->byteorder.byteorder; size_t offset = index * self->bytes_per_pixel; - if (self->pre_brightness_buffer != NULL) { - uint8_t* pre_brightness_buffer = self->pre_brightness_buffer + offset; - if (self->bytes_per_pixel == 4) { - pre_brightness_buffer[rgbw_order->w] = w; - } - - pre_brightness_buffer[rgbw_order->r] = r; - pre_brightness_buffer[rgbw_order->g] = g; - pre_brightness_buffer[rgbw_order->b] = b; + uint8_t *scaled_buffer, *unscaled_buffer; + if (self->pre_brightness_buffer) { + scaled_buffer = self->post_brightness_buffer + offset; + unscaled_buffer = self->pre_brightness_buffer + offset; + } else { + scaled_buffer = NULL; + unscaled_buffer = self->post_brightness_buffer + offset; } - uint8_t* post_brightness_buffer = self->post_brightness_buffer + offset; if (self->bytes_per_pixel == 4) { - // Only apply brightness if w is actually white (aka not DotStar.) - if (!self->byteorder.is_dotstar) { - w *= self->brightness; + unscaled_buffer[rgbw_order->w] = w; + } + + unscaled_buffer[rgbw_order->r] = r; + unscaled_buffer[rgbw_order->g] = g; + unscaled_buffer[rgbw_order->b] = b; + + if (scaled_buffer) { + if (self->bytes_per_pixel == 4) { + if (!self->byteorder.is_dotstar) { + w = (w * self->scaled_brightness) / 256; + } + scaled_buffer[rgbw_order->w] = w; } - post_brightness_buffer[rgbw_order->w] = w; + scaled_buffer[rgbw_order->r] = (r * self->scaled_brightness) / 256; + scaled_buffer[rgbw_order->g] = (g * self->scaled_brightness) / 256; + scaled_buffer[rgbw_order->b] = (b * self->scaled_brightness) / 256; } - post_brightness_buffer[rgbw_order->r] = r * self->brightness; - post_brightness_buffer[rgbw_order->g] = g * self->brightness; - post_brightness_buffer[rgbw_order->b] = b * self->brightness; } -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; @@ -230,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) { @@ -260,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); @@ -268,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; } @@ -293,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); @@ -303,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/_pixelbuf/PixelBuf.h b/shared-module/_pixelbuf/PixelBuf.h index a9fbed366fee0..f0c80bcad70a3 100644 --- a/shared-module/_pixelbuf/PixelBuf.h +++ b/shared-module/_pixelbuf/PixelBuf.h @@ -49,7 +49,8 @@ typedef struct { typedef struct { mp_obj_base_t base; size_t pixel_count; - size_t bytes_per_pixel; + uint16_t bytes_per_pixel; + uint16_t scaled_brightness; pixelbuf_byteorder_details_t byteorder; mp_float_t brightness; mp_obj_t transmit_buffer_obj; diff --git a/shared-module/_stage/Layer.c b/shared-module/_stage/Layer.c index d958f0d197037..df2b27fa131b1 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 df5bf80080ef0..91223f5258086 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 6dfc188801304..06a12aa0a71db 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 7a1826200e81b..5cbaa235b68b8 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 6d80cf599d92b..51c5073a74372 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 e489fc7c0791d..f34bb99f95f26 100644 --- a/shared-module/adafruit_bus_device/SPIDevice.c +++ b/shared-module/adafruit_bus_device/SPIDevice.c @@ -41,19 +41,34 @@ void common_hal_adafruit_bus_device_spidevice_construct(adafruit_bus_device_spid self->chip_select = cs; } -void common_hal_adafruit_bus_device_spidevice_enter(adafruit_bus_device_spidevice_obj_t *self) { - bool success = false; - while (!success) { - success = common_hal_busio_spi_try_lock(self->spi); - RUN_BACKGROUND_TASKS; - mp_handle_pending(); +mp_obj_t common_hal_adafruit_bus_device_spidevice_enter(adafruit_bus_device_spidevice_obj_t *self) { + { + mp_obj_t dest[2]; + mp_load_method(self->spi, MP_QSTR_try_lock, dest); + + while (!mp_obj_is_true(mp_call_method_n_kw(0, 0, dest))) { + mp_handle_pending(); + } } - common_hal_busio_spi_configure(self->spi, self->baudrate, self->polarity, self->phase, 8); + { + mp_obj_t dest[10]; + mp_load_method(self->spi, MP_QSTR_configure, dest); + dest[2] = MP_OBJ_NEW_QSTR(MP_QSTR_baudrate); + dest[3] = MP_OBJ_NEW_SMALL_INT(self->baudrate); + dest[4] = MP_OBJ_NEW_QSTR(MP_QSTR_polarity); + dest[5] = MP_OBJ_NEW_SMALL_INT(self->polarity); + dest[6] = MP_OBJ_NEW_QSTR(MP_QSTR_phase); + dest[7] = MP_OBJ_NEW_SMALL_INT(self->phase); + dest[8] = MP_OBJ_NEW_QSTR(MP_QSTR_bits); + dest[9] = MP_OBJ_NEW_SMALL_INT(8); + mp_call_method_n_kw(0, 4, dest); + } if (self->chip_select != MP_OBJ_NULL) { common_hal_digitalio_digitalinout_set_value(MP_OBJ_TO_PTR(self->chip_select), false); } + return self->spi; } void common_hal_adafruit_bus_device_spidevice_exit(adafruit_bus_device_spidevice_obj_t *self) { @@ -66,20 +81,21 @@ void common_hal_adafruit_bus_device_spidevice_exit(adafruit_bus_device_spidevice mp_buffer_info_t bufinfo; 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; + mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_WRITE); + ((uint8_t *)bufinfo.buf)[0] = 0xFF; - uint8_t clocks = self->extra_clocks / 8; - if ((self->extra_clocks % 8) != 0) - clocks += 1; + uint8_t clocks = (self->extra_clocks + 7) / 8; + mp_obj_t dest[3]; + mp_load_method(self->spi, MP_QSTR_write, dest); + dest[2] = buffer; while (clocks > 0) { - if (!common_hal_busio_spi_write(self->spi, ((uint8_t*)bufinfo.buf), 1)) { - mp_raise_OSError(MP_EIO); - } + mp_call_method_n_kw(1, 0, dest); clocks--; } } - common_hal_busio_spi_unlock(self->spi); + mp_obj_t dest[2]; + mp_load_method(self->spi, MP_QSTR_unlock, dest); + mp_call_method_n_kw(0, 0, dest); } diff --git a/shared-module/aesio/__init__.c b/shared-module/aesio/__init__.c index 2cacaeb66e79b..bd748f9800a66 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 b62b5afc48fde..f417e76de6466 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); - - 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) - { - { - k = (i - 1) * 4; - tempa[0]=RoundKey[k + 0]; - tempa[1]=RoundKey[k + 1]; - tempa[2]=RoundKey[k + 2]; - tempa[3]=RoundKey[k + 3]; +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 - if (i % ctx->Nk == 0) + // The first round key is the key itself. + for (i = 0; i < ctx->Nk; ++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]; + 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 defined(AES256) && (AES256 == 1) - if (ctx->KeyLength == 32) { - if (i % ctx->Nk == 4) - { - // Function Subword() + + // All other round keys are found from the previous round keys. + for (i = ctx->Nk; i < Nb * (ctx->Nr + 1); ++i) + { { - 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; - - // 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; - - 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; +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 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; + + // 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]; - - (*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); - } +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); + } } // 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; - - // 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; - - 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; +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 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; + + // 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; - - // 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; +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); + + // 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; - - // 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; +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); + + // 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); - - /* 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; + 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; + } + 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 a87fa5be75613..92539f1dab588 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 a69ddeb65038a..1f1db0a509ac6 100644 --- a/shared-module/audiocore/RawSample.c +++ b/shared-module/audiocore/RawSample.c @@ -30,53 +30,52 @@ #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; self->len = len; self->channel_count = channel_count; self->sample_rate = sample_rate; - self->buffer_read = false; } -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); @@ -86,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 6c2c19c9bfc0c..8208b4c2808d6 100644 --- a/shared-module/audiocore/RawSample.h +++ b/shared-module/audiocore/RawSample.h @@ -33,27 +33,26 @@ typedef struct { mp_obj_base_t base; - uint8_t* buffer; + uint8_t *buffer; uint32_t len; uint8_t bits_per_sample; bool samples_signed; uint8_t channel_count; uint32_t sample_rate; - bool buffer_read; } audioio_rawsample_obj_t; // 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 0248d42e221c2..4864004d52e21 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 3eecbf15ce36a..80b2fd3a565d3 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 7bdfe460ce419..605eac70b9ce9 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 ec2cf1cfab0b2..69955a25f718b 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 6c1ba1973e72e..20731933c40d1 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]); } @@ -103,33 +103,78 @@ void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t* self, __attribute__((always_inline)) static inline uint32_t add16signed(uint32_t a, uint32_t b) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __QADD16(a, b); + #else + uint32_t result = 0; + for (int8_t i = 0; i < 2; i++) { + int16_t ai = a >> (sizeof(int16_t) * 8 * i); + int16_t bi = b >> (sizeof(int16_t) * 8 * i); + int32_t intermediate = (int32_t)ai + bi; + if (intermediate > SHRT_MAX) { + intermediate = SHRT_MAX; + } else if (intermediate < SHRT_MIN) { + intermediate = SHRT_MIN; + } + result |= (((uint32_t)intermediate) & 0xffff) << (sizeof(int16_t) * 8 * i); + } + return result; + #endif } __attribute__((always_inline)) static inline uint32_t mult16signed(uint32_t val, int32_t mul) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) mul <<= 16; 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; + #else + uint32_t result = 0; + float mod_mul = (float)mul / (float)((1 << 15) - 1); + for (int8_t i = 0; i < 2; i++) { + int16_t ai = (val >> (sizeof(uint16_t) * 8 * i)); + int32_t intermediate = ai * mod_mul; + if (intermediate > SHRT_MAX) { + intermediate = SHRT_MAX; + } else if (intermediate < SHRT_MIN) { + intermediate = SHRT_MIN; + } + intermediate &= 0x0000FFFF; + result |= (((uint32_t)intermediate)) << (sizeof(int16_t) * 8 * i); + } + return result; + #endif } static inline uint32_t tounsigned8(uint32_t val) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __UADD8(val, 0x80808080); + #else + return val ^ 0x80808080; + #endif } static inline uint32_t tounsigned16(uint32_t val) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __UADD16(val, 0x80008000); + #else + return val ^ 0x80008000; + #endif } static inline uint32_t tosigned16(uint32_t val) { + #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) return __UADD16(val, 0x80008000); + #else + return val ^ 0x80008000; + #endif } static inline uint32_t unpack8(uint16_t val) { @@ -140,9 +185,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 +200,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 +215,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 +241,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 +273,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 +309,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 +351,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 ab4780efc6ca7..ceb04772ec185 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 9be104afcff5a..34fa907a5b527 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 a85316e3d0058..1fdc91d11baad 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 5f3f42a51bbea..2b623233e0d08 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 f91f102a2750f..c1e6178465ee4 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 d44aec0e7503c..7d7380e214fdc 100644 --- a/shared-module/bitbangio/I2C.c +++ b/shared-module/bitbangio/I2C.c @@ -32,7 +32,6 @@ #include "common-hal/microcontroller/Pin.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-module/bitbangio/types.h" #include "supervisor/shared/translate.h" STATIC void delay(bitbangio_i2c_obj_t *self) { @@ -144,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; @@ -209,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; @@ -233,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/types.h b/shared-module/bitbangio/I2C.h similarity index 71% rename from shared-module/bitbangio/types.h rename to shared-module/bitbangio/I2C.h index 6d17234741808..763c03adc6563 100644 --- a/shared-module/bitbangio/types.h +++ b/shared-module/bitbangio/I2C.h @@ -24,8 +24,8 @@ * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_TYPES_H -#define MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_TYPES_H +#ifndef MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_I2C_H +#define MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_I2C_H #include "common-hal/digitalio/DigitalInOut.h" @@ -40,22 +40,4 @@ typedef struct { volatile bool locked; } bitbangio_i2c_obj_t; -typedef struct { - mp_obj_base_t base; - digitalio_digitalinout_obj_t pin; -} bitbangio_onewire_obj_t; - -typedef struct { - mp_obj_base_t base; - digitalio_digitalinout_obj_t clock; - 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; -} bitbangio_spi_obj_t; - -#endif // MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_TYPES_H +#endif // MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_I2C_H diff --git a/shared-module/bitbangio/OneWire.c b/shared-module/bitbangio/OneWire.c index f5f4790876fbc..8a73817f37927 100644 --- a/shared-module/bitbangio/OneWire.c +++ b/shared-module/bitbangio/OneWire.c @@ -28,21 +28,20 @@ #include "shared-bindings/bitbangio/OneWire.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-module/bitbangio/types.h" // 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; } @@ -52,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); @@ -64,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); @@ -79,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/OneWire.h b/shared-module/bitbangio/OneWire.h new file mode 100644 index 0000000000000..bc4cb2096f46f --- /dev/null +++ b/shared-module/bitbangio/OneWire.h @@ -0,0 +1,39 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Scott Shawcroft + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_ONEWIRE_H +#define MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_ONEWIRE_H + +#include "common-hal/digitalio/DigitalInOut.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + digitalio_digitalinout_obj_t pin; +} bitbangio_onewire_obj_t; + +#endif // MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_ONEWIRE_H diff --git a/shared-module/bitbangio/SPI.c b/shared-module/bitbangio/SPI.c index f3fe16029aab1..65511964a6e1b 100644 --- a/shared-module/bitbangio/SPI.c +++ b/shared-module/bitbangio/SPI.c @@ -29,16 +29,16 @@ #include "py/runtime.h" #include "common-hal/microcontroller/Pin.h" -#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/bitbangio/SPI.h" #include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-module/bitbangio/types.h" +#include "shared-bindings/microcontroller/__init__.h" #include "supervisor/shared/translate.h" #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) { @@ -176,7 +176,7 @@ bool shared_module_bitbangio_spi_write(bitbangio_spi_obj_t *self, const uint8_t } // Reads in len bytes while outputting zeroes. -bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, size_t len) { +bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_data) { if (len > 0 && !self->has_miso) { mp_raise_ValueError(translate("Cannot read without MISO pin.")); } @@ -210,8 +210,12 @@ bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, common_hal_digitalio_digitalinout_set_value(&self->mosi, false); } for (size_t i = 0; i < len; ++i) { + uint8_t data_out = write_data; uint8_t data_in = 0; - for (int j = 0; j < 8; ++j) { + for (int j = 0; j < 8; ++j, data_out <<= 1) { + if (self->has_mosi) { + common_hal_digitalio_digitalinout_set_value(&self->mosi, (data_out >> 7) & 1); + } if (self->phase == 0) { common_hal_mcu_delay_us(delay_half); common_hal_digitalio_digitalinout_set_value(&self->clock, 1 - self->polarity); @@ -241,7 +245,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 new file mode 100644 index 0000000000000..cc71a0319a8ce --- /dev/null +++ b/shared-module/bitbangio/SPI.h @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Scott Shawcroft + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_SPI_H +#define MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_SPI_H + +#include "common-hal/digitalio/DigitalInOut.h" + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + digitalio_digitalinout_obj_t clock; + 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; +} 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 new file mode 100644 index 0000000000000..4c8b8872006cd --- /dev/null +++ b/shared-module/bitmaptools/__init__.c @@ -0,0 +1,466 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Kevin Matocha + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +#include "shared-bindings/bitmaptools/__init__.h" +#include "shared-bindings/displayio/Bitmap.h" +#include "shared-module/displayio/Bitmap.h" + +#include "py/runtime.h" +#include "py/mperrno.h" + +#include "math.h" +#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) { + + // Copies region from source to the destination bitmap, including rotation, + // scaling and clipping of either the source or destination regions + // + // *self: destination bitmap + // ox: the (ox, oy) destination point where the source (px,py) point is placed + // oy: + // dest_clip0: (x,y) is the corner of the clip window on the destination bitmap + // dest_clip1: (x,y) is the other corner of the clip window of the destination bitmap + // *source: the source bitmap + // px: the (px, py) point of rotation of the source bitmap + // py: + // source_clip0: (x,y) is the corner of the clip window on the source bitmap + // source_clip1: (x,y) is the other of the clip window on the source bitmap + // angle: angle of rotation in radians, positive is clockwise + // scale: scale factor + // skip_index: color index that should be ignored (and not copied over) + // skip_index_none: if skip_index_none is True, then all color indexes should be copied + // (that is, no color indexes should be skipped) + + + // Copy complete "source" bitmap into "self" bitmap at location x,y in the "self" + // Add a boolean to determine if all values are copied, or only if non-zero + // If skip_value is encountered in the source bitmap, it will not be copied. + // If skip_value is `None`, then all pixels are copied. + + + // # Credit from https://github.com/wernsey/bitmap + // # MIT License from + // # * Copyright (c) 2017 Werner Stoop + // # + // # * + // # * #### `void bm_rotate_blit(Bitmap *dst, int ox, int oy, Bitmap *src, int px, int py, double angle, double scale);` + // # * + // # * Rotates a source bitmap `src` around a pivot point `px,py` and blits it onto a destination bitmap `dst`. + // # * + // # * The bitmap is positioned such that the point `px,py` on the source is at the offset `ox,oy` on the destination. + // # * + // # * The `angle` is clockwise, in radians. The bitmap is also scaled by the factor `scale`. + // # + // # void bm_rotate_blit(Bitmap *dst, int ox, int oy, Bitmap *src, int px, int py, double angle, double scale); + + + // # /* + // # Reference: + // # "Fast Bitmap Rotation and Scaling" By Steven Mortimer, Dr Dobbs' Journal, July 01, 2001 + // # http://www.drdobbs.com/architecture-and-design/fast-bitmap-rotation-and-scaling/184416337 + // # See also http://www.efg2.com/Lab/ImageProcessing/RotateScanline.htm + // # */ + + + int16_t x,y; + + int16_t minx = dest_clip1_x; + int16_t miny = dest_clip1_y; + int16_t maxx = dest_clip0_x; + int16_t maxy = dest_clip0_y; + + float sinAngle = sinf(angle); + float cosAngle = cosf(angle); + + float dx, dy; + + /* Compute the position of where each corner on the source bitmap + 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; + } + + 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; + } + + 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; + } + + 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; + } + + /* 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; + } + + float dvCol = cosAngle / scale; + float duCol = sinAngle / scale; + + float duRow = dvCol; + float dvRow = -duCol; + + float startu = px - (ox * dvCol + oy * duCol); + float startv = py - (ox * dvRow + oy * duRow); + + float rowu = startu + miny * duCol; + float rowv = startv + miny * dvCol; + + displayio_area_t dirty_area = {minx, miny, maxx + 1, maxy + 1}; + displayio_bitmap_set_dirty_area(self, &dirty_area); + + 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) { + uint32_t c = common_hal_displayio_bitmap_get_pixel(source, u, v); + if ((skip_index_none) || (c != skip_index)) { + displayio_bitmap_write_pixel(self, x, y, c); + } + } + u += duRow; + v += dvRow; + } + rowu += duCol; + rowv += dvCol; + } +} + +int16_t constrain(int16_t input, int16_t min, int16_t max) { + // constrain the input between the min and max values + if (input < min) { + return min; + } + if (input > max) { + return max; + } + return input; +} + +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) { + // 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 + + displayio_area_t area = { x1, y1, x2, y2 }; + displayio_area_canon(&area); + + displayio_area_t bitmap_area = { 0, 0, destination->width, destination->height }; + displayio_area_compute_overlap(&area, &bitmap_area, &area); + + // update the dirty rectangle + displayio_bitmap_set_dirty_area(destination, &area); + + int16_t x, y; + for (x = area.x1; x < area.x2; x++) { + for (y = area.y1; y < area.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) { + + // + // adapted from Adafruit_CircuitPython_Display_Shapes.Polygon._line + // + + // update the dirty rectangle + int16_t xbb0, xbb1, ybb0, ybb1; + if (x0 < x1) { + xbb0 = x0; + xbb1 = x1 + 1; + } else { + xbb0 = x1; + xbb1 = x0 + 1; + } + if (y0 < y1) { + ybb0 = y0; + ybb1 = y1 + 1; + } else { + ybb0 = y1; + ybb1 = y0 + 1; + } + displayio_area_t area = { xbb0, ybb0, xbb1, ybb1 }; + displayio_area_t bitmap_area = { 0, 0, destination->width, destination->height }; + displayio_area_compute_overlap(&area, &bitmap_area, &area); + + displayio_bitmap_set_dirty_area(destination, &area); + + int16_t temp, x, y; + + if (x0 == x1) { // vertical line + if (y0 > y1) { // ensure y1 > y0 + temp = y0; + y0 = y1; + y1 = temp; + } + 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 + if (x0 > x1) { // ensure y1 > y0 + temp = x0; + x0 = x1; + x1 = temp; + } + for (x = x0; x < (x1 + 1); x++) { // write a horizontal line + displayio_bitmap_write_pixel(destination, x, y0, value); + } + } else { + bool steep; + steep = (abs(y1 - y0) > abs(x1 - x0)); + + if (steep) { // flip x0<->y0 and x1<->y1 + temp = x0; + x0 = y0; + y0 = temp; + temp = x1; + x1 = y1; + y1 = temp; + } + + if (x0 > x1) { // flip x0<->x1 and y0<->y1 + temp = x0; + x0 = x1; + x1 = temp; + temp = y0; + y0 = y1; + y1 = temp; + } + + int16_t dx, dy, ystep; + dx = x1 - x0; + dy = abs(y1 - y0); + + float err = dx / 2; + + if (y0 < y1) { + ystep = 1; + } else { + ystep = -1; + } + + for (x = x0; x < (x1 + 1); x++) { + if (steep) { + displayio_bitmap_write_pixel(destination, y0, x, value); + } else { + displayio_bitmap_write_pixel(destination, x, y0, value); + } + err -= dy; + if (err < 0) { + y0 += ystep; + err += dx; + } + } + } +} + +void common_hal_bitmaptools_arrayblit(displayio_bitmap_t *self, void *data, int element_size, int x1, int y1, int x2, int y2, bool skip_specified, uint32_t skip_value) { + uint32_t mask = (1 << common_hal_displayio_bitmap_get_bits_per_value(self)) - 1; + + for (int y = y1; y < y2; y++) { + for (int x = x1; x < x2; x++) { + uint32_t value; + switch (element_size) { + default: + case 1: + value = *(uint8_t *)data; + data = (void *)((uint8_t *)data + 1); + break; + case 2: + value = *(uint16_t *)data; + data = (void *)((uint16_t *)data + 1); + break; + case 4: + value = *(uint32_t *)data; + data = (void *)((uint32_t *)data + 1); + break; + } + if (!skip_specified || value != skip_value) { + displayio_bitmap_write_pixel(self, x, y, value & mask); + } + } + } + displayio_area_t area = { x1, y1, x2, y2 }; + displayio_bitmap_set_dirty_area(self, &area); +} + +void common_hal_bitmaptools_readinto(displayio_bitmap_t *self, pyb_file_obj_t *file, int element_size, int bits_per_pixel, bool reverse_pixels_in_element, bool swap_bytes, bool reverse_rows) { + uint32_t mask = (1 << common_hal_displayio_bitmap_get_bits_per_value(self)) - 1; + + displayio_area_t a = {0, 0, self->width, self->height}; + displayio_bitmap_set_dirty_area(self, &a); + + size_t elements_per_row = (self->width * bits_per_pixel + element_size * 8 - 1) / (element_size * 8); + size_t rowsize = element_size * elements_per_row; + size_t rowsize_in_u32 = (rowsize + sizeof(uint32_t) - 1) / sizeof(uint32_t); + size_t rowsize_in_u16 = (rowsize + sizeof(uint16_t) - 1) / sizeof(uint16_t); + + for (int y = 0; y < self->height; y++) { + uint32_t rowdata32[rowsize_in_u32]; + uint16_t *rowdata16 = (uint16_t *)rowdata32; + uint8_t *rowdata8 = (uint8_t *)rowdata32; + const int y_draw = reverse_rows ? (self->height) - 1 - y : y; + + UINT bytes_read = 0; + if (f_read(&file->fp, rowdata32, rowsize, &bytes_read) != FR_OK || bytes_read != rowsize) { + mp_raise_OSError(MP_EIO); + } + + if (swap_bytes) { + switch (element_size) { + case 2: + for (size_t i = 0; i < rowsize_in_u16; i++) { + rowdata16[i] = __builtin_bswap16(rowdata16[i]); + } + break; + case 4: + for (size_t i = 0; i < rowsize_in_u32; i++) { + rowdata32[i] = __builtin_bswap32(rowdata32[i]); + } + default: + break; + } + } + + for (int x = 0; x < self->width; x++) { + int value = 0; + switch (bits_per_pixel) { + case 1: { + int byte_offset = x / 8; + int bit_offset = reverse_pixels_in_element ? (7 - x % 8) : x % 8; + + value = (rowdata8[byte_offset] >> bit_offset) & 1; + break; + } + case 2: { + int byte_offset = x / 4; + int bit_offset = 2 * (reverse_pixels_in_element ? (3 - x % 4) : x % 4); + + value = (rowdata8[byte_offset] >> bit_offset) & 3; + break; + } + case 4: { + int byte_offset = x / 2; + int bit_offset = 4 * (reverse_pixels_in_element ? (1 - x % 2) : x % 2); + + value = (rowdata8[byte_offset] >> bit_offset) & 0xf; + break; + } + case 8: + value = rowdata8[x]; + break; + + case 16: + value = rowdata16[x]; + break; + + case 24: + value = (rowdata8[x * 3] << 16) | (rowdata8[x * 3 + 1] << 8) | (rowdata8[x * 3 + 2] << 8); + break; + + case 32: + value = rowdata32[x]; + break; + } + displayio_bitmap_write_pixel(self, x, y_draw, value & mask); + } + } +} diff --git a/shared-module/bitops/__init__.c b/shared-module/bitops/__init__.c new file mode 100644 index 0000000000000..168989218115b --- /dev/null +++ b/shared-module/bitops/__init__.c @@ -0,0 +1,167 @@ +/* + * This file is part of the Circuit Python project, https://github.com/adafruit/circuitpython + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "shared-bindings/bitops/__init__.h" + +#include +#include +#include + +#ifdef __GNUC__ +#define FALLTHROUGH __attribute__((fallthrough)) +#else +#define FALLTHROUGH ((void)0) /* FALLTHROUGH */ +#endif + +// adapted from "Hacker's Delight" - Figure 7-2 Transposing an 8x8-bit matrix +// basic idea is: +// > First, treat the 8x8-bit matrix as 16 2x2-bit matrices, and transpose each +// > of the 16 2x2-bit matrices. Second, treat the matrix as four 2x2 submatrices +// > whose elements are 2x2-bit matrices and transpose each of the four 2x2 +// > submatrices. Finally, treat the matrix as a 2x2 matrix whose elements are +// > 4x4-bit matrices, and transpose the 2x2 matrix. These transformations are +// > illustrated below. +// We want a different definition of bit/byte order, deal with strides differently, etc. +// so the code is heavily re-worked compared to the original. +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; + + 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 >> 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__ + x = __builtin_bswap32(x); + y = __builtin_bswap32(y); + #endif + result[0] = x; + result[1] = y; +} + +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; + + 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 & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); + y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); + x = t; + + #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + x = __builtin_bswap32(x); + y = __builtin_bswap32(y); + #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; i < n; i++) { + transpose_8(result, src, src_stride); + result += 2; + src += 1; + } +} + +static void bit_transpose_var(uint32_t *result, const uint8_t *src, size_t src_stride, size_t n, int num_strands) { + for (size_t i = 0; i < n; i++) { + transpose_var(result, src, src_stride, num_strands); + result += 2; + src += 1; + } +} + +void common_hal_bitops_bit_transpose(uint8_t *result, const uint8_t *src, size_t inlen, size_t num_strands) { + if (num_strands == 8) { + bit_transpose_8((uint32_t *)(void *)result, src, inlen / 8, inlen / 8); + } else { + bit_transpose_var((uint32_t *)(void *)result, src, inlen / num_strands, inlen / num_strands, num_strands); + } +} diff --git a/shared-module/bitops/__init__.h b/shared-module/bitops/__init__.h new file mode 100644 index 0000000000000..945e48b722a47 --- /dev/null +++ b/shared-module/bitops/__init__.h @@ -0,0 +1,27 @@ +/* + * This file is part of the Circuit Python project, https://github.com/adafruit/circuitpython + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once diff --git a/shared-module/board/__init__.c b/shared-module/board/__init__.c index 2f1c34e565cad..9dbca48fd1916 100644 --- a/shared-module/board/__init__.c +++ b/shared-module/board/__init__.c @@ -60,7 +60,7 @@ mp_obj_t common_hal_board_create_i2c(void) { busio_i2c_obj_t *self = &i2c_obj; self->base.type = &busio_i2c_type; - common_hal_busio_i2c_construct(self, DEFAULT_I2C_BUS_SCL, DEFAULT_I2C_BUS_SDA, 100000, 0); + common_hal_busio_i2c_construct(self, DEFAULT_I2C_BUS_SCL, DEFAULT_I2C_BUS_SDA, 100000, 255); i2c_singleton = (mp_obj_t)self; return i2c_singleton; } @@ -83,9 +83,9 @@ mp_obj_t common_hal_board_create_spi(void) { busio_spi_obj_t *self = &spi_obj; self->base.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 06e1af10a1cbc..d3db18e3ad2ab 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/I2C.h b/shared-module/busio/I2C.h index 8e3525f196caa..e089ea367b951 100644 --- a/shared-module/busio/I2C.h +++ b/shared-module/busio/I2C.h @@ -27,7 +27,7 @@ #ifndef MICROPY_INCLUDED_ATMEL_SAMD_SHARED_MODULE_BUSIO_I2C_H #define MICROPY_INCLUDED_ATMEL_SAMD_SHARED_MODULE_BUSIO_I2C_H -#include "shared-module/bitbangio/types.h" +#include "shared-module/bitbangio/I2C.h" #include "py/obj.h" diff --git a/shared-module/busio/OneWire.c b/shared-module/busio/OneWire.c index 6bb7dedcd17f7..80c55c7b2ba7b 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/busio/OneWire.h b/shared-module/busio/OneWire.h index 9ffb89d497d7c..5d80bab17ce75 100644 --- a/shared-module/busio/OneWire.h +++ b/shared-module/busio/OneWire.h @@ -27,7 +27,7 @@ #ifndef MICROPY_INCLUDED_ATMEL_SAMD_SHARED_MODULE_BUSIO_ONEWIRE_H #define MICROPY_INCLUDED_ATMEL_SAMD_SHARED_MODULE_BUSIO_ONEWIRE_H -#include "shared-module/bitbangio/types.h" +#include "shared-module/bitbangio/OneWire.h" #include "py/obj.h" diff --git a/shared-module/canio/Message.c b/shared-module/canio/Message.c index a1df4f693d043..08e4d9fda7da4 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 1ca0d42e2c5d3..fafcaffe7a39d 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 9b4d5632f8e2c..55c0d3ba22f57 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 d1942efc79bf9..e218049b6c28b 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,68 +93,35 @@ 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; } -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) { - // Copy complete "source" bitmap into "self" bitmap at location x,y in the "self" - // Add a boolean to determine if all values are copied, or only if non-zero - // If skip_value is encountered in the source bitmap, it will not be copied. - // If skip_value is `None`, then all pixels are copied. - +void displayio_bitmap_set_dirty_area(displayio_bitmap_t *self, const displayio_area_t *dirty_area) { if (self->read_only) { mp_raise_RuntimeError(translate("Read-only object")); } - // simplest version - use internal functions for get/set pixels - for (int16_t i=0; i < (x2-x1) ; i++) { - if ( (x+i >= 0) && (x+i < self->width) ) { - for (int16_t j=0; j < (y2-y1) ; j++){ - if ((y+j >= 0) && (y+j < self->height) ) { - uint32_t value = common_hal_displayio_bitmap_get_pixel(source, x1+i, y1+j); - if ( (skip_index_none) || (value != skip_index) ) { // write if skip_value_none is True - common_hal_displayio_bitmap_set_pixel(self, x+i, y+j, value); - } - } - } - } - } + displayio_area_t area = *dirty_area; + displayio_area_canon(&area); + displayio_area_union(&area, &self->dirty_area, &area); + displayio_area_t bitmap_area = {0, 0, self->width, self->height}; + displayio_area_compute_overlap(&area, &bitmap_area, &self->dirty_area); } -void common_hal_displayio_bitmap_set_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) { - if (self->read_only) { - mp_raise_RuntimeError(translate("Read-only object")); - } - // Update the dirty area. - if (self->dirty_area.x1 == self->dirty_area.x2) { - self->dirty_area.x1 = x; - self->dirty_area.x2 = x + 1; - self->dirty_area.y1 = y; - self->dirty_area.y2 = y + 1; - } else { - if (x < self->dirty_area.x1) { - self->dirty_area.x1 = x; - } else if (x >= self->dirty_area.x2) { - self->dirty_area.x2 = x + 1; - } - if (y < self->dirty_area.y1) { - self->dirty_area.y1 = y; - } else if (y >= self->dirty_area.y2) { - self->dirty_area.y2 = y + 1; - } - } +void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) { + // Writes the color index value into a pixel position + // Must update the dirty area separately - // Update our data + // Update one pixel of data int32_t row_start = y * self->stride; uint32_t bytes_per_value = self->bits_per_value / 8; if (bytes_per_value < 1) { @@ -165,18 +132,82 @@ void common_hal_displayio_bitmap_set_pixel(displayio_bitmap_t *self, int16_t x, 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) { + // 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. + // This function assumes input checks were performed for pixel index entries. + + // Update the dirty area + 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); + if (dirty_y_max > self->height) { + dirty_y_max = self->height; + } + + displayio_area_t a = { x, y, dirty_x_max, dirty_y_max}; + displayio_bitmap_set_dirty_area(self, &a); + + bool x_reverse = false; + bool y_reverse = false; + + // Add reverse direction option to protect blitting of self bitmap back into self bitmap + if (x > x1) { + x_reverse = true; + } + if (y > y1) { + y_reverse = true; + } + + // simplest version - use internal functions for get/set pixels + 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 + + 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 + + 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); + } + } + } } } } -displayio_area_t* displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t* tail) { +void common_hal_displayio_bitmap_set_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) { + // update the dirty region + displayio_area_t a = {x, y, x + 1, y + 1}; + displayio_bitmap_set_dirty_area(self, &a); + + // 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) { if (self->dirty_area.x1 == self->dirty_area.x2) { return tail; } @@ -190,22 +221,36 @@ void displayio_bitmap_finish_refresh(displayio_bitmap_t *self) { } void common_hal_displayio_bitmap_fill(displayio_bitmap_t *self, uint32_t value) { - if (self->read_only) { - mp_raise_RuntimeError(translate("Read-only object")); - } - // Update the dirty area. - self->dirty_area.x1 = 0; - self->dirty_area.x2 = self->width; - self->dirty_area.y1 = 0; - self->dirty_area.y2 = self->height; + displayio_area_t a = {0, 0, self->width, self->height}; + displayio_bitmap_set_dirty_area(self, &a); // 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; } } + +int common_hal_displayio_bitmap_get_buffer(displayio_bitmap_t *self, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + if ((flags & MP_BUFFER_WRITE) && self->read_only) { + return 1; + } + bufinfo->len = self->stride * self->height * sizeof(size_t); + bufinfo->buf = self->data; + switch (self->bits_per_value) { + case 32: + bufinfo->typecode = 'I'; + break; + case 16: + bufinfo->typecode = 'H'; + break; + default: + bufinfo->typecode = 'B'; + break; + } + return 0; +} diff --git a/shared-module/displayio/Bitmap.h b/shared-module/displayio/Bitmap.h index f4bd7ce4d328a..82a3de631a209 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,6 +48,8 @@ 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, const displayio_area_t *area); +void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_BITMAP_H diff --git a/shared-module/displayio/ColorConverter.c b/shared-module/displayio/ColorConverter.c index 40dcd9d167818..47cb903f3f32d 100644 --- a/shared-module/displayio/ColorConverter.c +++ b/shared-module/displayio/ColorConverter.c @@ -31,20 +31,20 @@ #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, displayio_colorspace_t input_colorspace) { self->dither = dither; self->transparent_color = NO_TRANSPARENT_COLOR; + self->input_colorspace = input_colorspace; } uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888) { @@ -83,11 +83,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 +96,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 +110,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 +124,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 +153,46 @@ void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _d return; } - if (self->dither){ + switch (self->input_colorspace) { + case DISPLAYIO_COLORSPACE_RGB565_SWAPPED: + pixel = __builtin_bswap16(pixel); + FALLTHROUGH; + case DISPLAYIO_COLORSPACE_RGB565: { + uint32_t r8 = (pixel >> 11) << 3; + uint32_t g8 = ((pixel >> 5) << 2) & 0xff; + uint32_t b8 = (pixel << 3) & 0xff; + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_RGB555_SWAPPED: + pixel = __builtin_bswap16(pixel); + FALLTHROUGH; + case DISPLAYIO_COLORSPACE_RGB555: { + uint32_t r8 = (pixel >> 10) << 3; + uint32_t g8 = ((pixel >> 5) << 3) & 0xff; + uint32_t b8 = (pixel << 3) & 0xff; + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_RGB888: + break; + } + + 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 +224,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 b402625ef7fed..55f86982dcdb3 100644 --- a/shared-module/displayio/ColorConverter.h +++ b/shared-module/displayio/ColorConverter.h @@ -36,20 +36,21 @@ typedef struct { mp_obj_base_t base; bool dither; + uint8_t input_colorspace; uint32_t transparent_color; } displayio_colorconverter_t; 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 7c8c9280b5c13..9117a50b786b5 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; @@ -111,7 +111,7 @@ void common_hal_displayio_display_construct(displayio_display_obj_t* self, self->backlight_inout.base.type = &mp_type_NoneType; if (backlight_pin != NULL && common_hal_mcu_pin_is_free(backlight_pin)) { // Avoid PWM types and functions when the module isn't enabled - #if (CIRCUITPY_PULSEIO) + #if (CIRCUITPY_PWMIO) pwmout_result_t result = common_hal_pwmio_pwmout_construct(&self->backlight_pwm, backlight_pin, 0, 50000, false); if (result != PWMOUT_OK) { self->backlight_inout.base.type = &digitalio_digitalinout_type; @@ -141,47 +141,47 @@ 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; // Avoid PWM types and functions when the module isn't enabled - #if (CIRCUITPY_PULSEIO) + #if (CIRCUITPY_PWMIO) bool ispwm = (self->backlight_pwm.base.type == &pwmio_pwmout_type) ? true : false; #else bool ispwm = false; #endif if (ispwm) { - #if (CIRCUITPY_PULSEIO) - common_hal_pwmio_pwmout_set_duty_cycle(&self->backlight_pwm, (uint16_t) (0xffff * brightness)); + #if (CIRCUITPY_PWMIO) + 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,21 +403,21 @@ 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; } if (supervisor_ticks_ms64() - self->last_backlight_refresh < 100) { return; } - // TODO(tannewt): Fade the backlight based on it's existing value and a target value. The target + // TODO(tannewt): Fade the backlight based on its existing value and a target value. The target // should account for ambient light when possible. common_hal_displayio_display_set_brightness(self, 1.0); 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,10 +425,10 @@ 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) + #if (CIRCUITPY_PWMIO) if (self->backlight_pwm.base.type == &pwmio_pwmout_type) { common_hal_pwmio_pwmout_reset_ok(&self->backlight_pwm); common_hal_pwmio_pwmout_deinit(&self->backlight_pwm); @@ -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 cc9cd54c405cd..a0049f00c0784 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 3fb37ff21916c..7eff587757021 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 d0668ff444e8f..988cc57fa344d 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 e993f2480c5b7..59e2021bd8c22 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 a4260a3ac50ca..b28c1ef8404d0 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 15cf5b8e48d20..d1bdae2c3337b 100644 --- a/shared-module/displayio/Group.c +++ b/shared-module/displayio/Group.c @@ -27,6 +27,7 @@ #include "shared-bindings/displayio/Group.h" #include "py/runtime.h" +#include "py/objlist.h" #include "shared-bindings/displayio/TileGrid.h" #if CIRCUITPY_VECTORIO @@ -34,16 +35,16 @@ #endif -void common_hal_displayio_group_construct(displayio_group_t* self, uint32_t max_size, uint32_t scale, mp_int_t x, mp_int_t y) { - displayio_group_child_t* children = m_new(displayio_group_child_t, max_size); - displayio_group_construct(self, children, max_size, scale, x, 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; } @@ -51,12 +52,19 @@ void common_hal_displayio_group_set_hidden(displayio_group_t* self, bool hidden) if (self->hidden_by_parent) { return; } - for (size_t i = 0; i < self->size; i++) { - mp_obj_t layer = self->children[i].native; - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { displayio_tilegrid_set_hidden_by_parent(layer, hidden); - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { + continue; + } + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { displayio_group_set_hidden_by_parent(layer, hidden); + continue; } } } @@ -70,39 +78,52 @@ void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden) if (self->hidden) { return; } - for (size_t i = 0; i < self->size; i++) { - mp_obj_t layer = self->children[i].native; - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { displayio_tilegrid_set_hidden_by_parent(layer, hidden); - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { + continue; + } + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { displayio_group_set_hidden_by_parent(layer, hidden); + continue; } } } -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->size; i++) { - mp_obj_t layer = self->children[i].native; + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; displayio_area_t layer_area; - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { if (!displayio_tilegrid_get_previous_area(layer, &layer_area)) { continue; } - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { - if (!displayio_group_get_previous_area(layer, &layer_area)) { - continue; + } else { + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { + if (!displayio_group_get_previous_area(layer, &layer_area)) { + continue; + } } } if (first) { displayio_area_copy(&layer_area, area); first = false; } else { - displayio_area_expand(area, &layer_area); + displayio_area_union(area, &layer_area, area); } } if (self->item_removed) { @@ -110,34 +131,43 @@ bool displayio_group_get_previous_area(displayio_group_t *self, displayio_area_t displayio_area_copy(&self->dirty_area, area); first = false; } else { - displayio_area_expand(area, &self->dirty_area); + displayio_area_union(area, &self->dirty_area, area); } } 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->size; i++) { - mp_obj_t layer = self->children[i].native; -#if CIRCUITPY_VECTORIO - if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) { + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; + #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; } - else -#endif - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { + #endif + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { displayio_tilegrid_update_transform(layer, &self->absolute_transform); - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { + continue; + } + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { displayio_group_update_transform(layer, &self->absolute_transform); + continue; } } } 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; @@ -159,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; } @@ -171,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); } @@ -191,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); } @@ -210,58 +240,64 @@ void common_hal_displayio_group_set_y(displayio_group_t* self, mp_int_t y) { _update_child_transforms(self); } -static mp_obj_t _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 native_layer; + return; } -#endif - native_layer = mp_instance_cast_to_native_base(layer, &displayio_group_type); - if (native_layer == MP_OBJ_NULL) { - native_layer = mp_instance_cast_to_native_base(layer, &displayio_tilegrid_type); - if (native_layer == MP_OBJ_NULL) { - mp_raise_ValueError(translate("Layer must be a Group or TileGrid subclass.")); - } - displayio_tilegrid_t* tilegrid = native_layer; + #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; if (tilegrid->in_group) { mp_raise_ValueError(translate("Layer already in a group.")); } else { tilegrid->in_group = true; } displayio_tilegrid_update_transform(tilegrid, &self->absolute_transform); - } else { - displayio_group_t* group = native_layer; + return; + } + native_layer = mp_instance_cast_to_native_base(layer, &displayio_group_type); + if (native_layer != MP_OBJ_NULL) { + displayio_group_t *group = native_layer; if (group->in_group) { mp_raise_ValueError(translate("Layer already in a group.")); } else { group->in_group = true; } displayio_group_update_transform(group, &self->absolute_transform); + return; } - return native_layer; + mp_raise_ValueError(translate("Layer must be a Group or TileGrid subclass.")); } -static void _remove_layer(displayio_group_t* self, size_t index) { - mp_obj_t layer = self->children[index].native; +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 (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) { + #if CIRCUITPY_VECTORIO + layer = mp_instance_cast_to_native_base( + self->members->items[index], &vectorio_vector_shape_type); + if (layer != MP_OBJ_NULL) { bool has_dirty_area = vectorio_vector_shape_get_dirty_area(layer, &layer_area); rendered_last_frame = has_dirty_area; vectorio_vector_shape_update_transform(layer, NULL); } - else -#endif - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { - displayio_tilegrid_t* tilegrid = layer; + #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; rendered_last_frame = displayio_tilegrid_get_previous_area(tilegrid, &layer_area); displayio_tilegrid_update_transform(tilegrid, NULL); - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { - displayio_group_t* group = layer; + } + layer = mp_instance_cast_to_native_base( + self->members->items[index], &displayio_group_type); + if (layer != MP_OBJ_NULL) { + displayio_group_t *group = layer; rendered_last_frame = displayio_group_get_previous_area(group, &layer_area); displayio_group_update_transform(group, NULL); } @@ -271,139 +307,140 @@ static void _remove_layer(displayio_group_t* self, size_t index) { if (!self->item_removed) { displayio_area_copy(&layer_area, &self->dirty_area); } else { - displayio_area_expand(&self->dirty_area, &layer_area); + displayio_area_union(&self->dirty_area, &layer_area, &self->dirty_area); } self->item_removed = true; } -void common_hal_displayio_group_insert(displayio_group_t* self, size_t index, mp_obj_t layer) { - if (self->size == self->max_size) { - mp_raise_RuntimeError(translate("Group full")); - } - mp_obj_t native_layer = _add_layer(self, layer); - // Shift everything right. - for (size_t i = self->size; i > index; i--) { - self->children[i] = self->children[i - 1]; - } - self->children[index].native = native_layer; - self->children[index].original = layer; - self->size++; +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) { - self->size--; - mp_obj_t item = self->children[index].original; +mp_obj_t common_hal_displayio_group_pop(displayio_group_t *self, size_t index) { _remove_layer(self, index); - - // Shift everything left. - for (size_t i = index; i < self->size; i++) { - self->children[i] = self->children[i + 1]; - } - self->children[self->size].native = NULL; - self->children[self->size].original = NULL; - return item; + return mp_obj_list_pop(self->members, index); } -mp_int_t common_hal_displayio_group_index(displayio_group_t* self, mp_obj_t layer) { - for (size_t i = 0; i < self->size; i++) { - if (self->children[i].original == layer) { - return i; - } - } - return -1; +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) { - return self->size; +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) { - return self->children[index].original; +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) { - mp_obj_t native_layer = _add_layer(self, 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); - self->children[index].native = native_layer; - self->children[index].original = layer; + mp_obj_list_store(self->members, MP_OBJ_NEW_SMALL_INT(index), layer); } -void displayio_group_construct(displayio_group_t* self, displayio_group_child_t* child_array, uint32_t max_size, 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->children = child_array; - self->max_size = max_size; + self->members = members; self->item_removed = false; self->scale = scale; 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. - bool full_coverage = false; - for (int32_t i = self->size - 1; i >= 0 ; i--) { - mp_obj_t layer = self->children[i].native; -#if CIRCUITPY_VECTORIO - if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) { + for (int32_t i = self->members->len - 1; i >= 0; i--) { + mp_obj_t layer; + #if CIRCUITPY_VECTORIO + layer = mp_instance_cast_to_native_base( + self->members->items[i], &vectorio_vector_shape_type); + if (layer != MP_OBJ_NULL) { if (vectorio_vector_shape_fill_area(layer, colorspace, area, mask, buffer)) { - full_coverage = true; - break; + return true; } + continue; } - else -#endif - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { + #endif + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { if (displayio_tilegrid_fill_area(layer, colorspace, area, mask, buffer)) { - full_coverage = true; - break; + return true; } - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { + continue; + } + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { if (displayio_group_fill_area(layer, colorspace, area, mask, buffer)) { - full_coverage = true; - break; + return true; } + continue; } } - return full_coverage; + return false; } void displayio_group_finish_refresh(displayio_group_t *self) { self->item_removed = false; - for (int32_t i = self->size - 1; i >= 0 ; i--) { - mp_obj_t layer = self->children[i].native; -#if CIRCUITPY_VECTORIO - if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) { + for (int32_t i = self->members->len - 1; i >= 0; i--) { + mp_obj_t layer; + #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; } - else -#endif - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { + #endif + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { displayio_tilegrid_finish_refresh(layer); - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { + continue; + } + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { displayio_group_finish_refresh(layer); + continue; } } } -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->size - 1; i >= 0 ; i--) { - mp_obj_t layer = self->children[i].native; -#if CIRCUITPY_VECTORIO - if (MP_OBJ_IS_TYPE(layer, &vectorio_vector_shape_type)) { + for (int32_t i = self->members->len - 1; i >= 0; i--) { + mp_obj_t layer; + #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; } - else -#endif - if (MP_OBJ_IS_TYPE(layer, &displayio_tilegrid_type)) { + #endif + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { tail = displayio_tilegrid_get_refresh_areas(layer, tail); - } else if (MP_OBJ_IS_TYPE(layer, &displayio_group_type)) { + continue; + } + layer = mp_instance_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { tail = displayio_group_get_refresh_areas(layer, tail); + continue; } } diff --git a/shared-module/displayio/Group.h b/shared-module/displayio/Group.h index 5afaac1bae168..f6842231544ba 100644 --- a/shared-module/displayio/Group.h +++ b/shared-module/displayio/Group.h @@ -31,37 +31,31 @@ #include #include "py/obj.h" +#include "py/objlist.h" #include "shared-module/displayio/area.h" #include "shared-module/displayio/Palette.h" -typedef struct { - mp_obj_t native; - mp_obj_t original; -} displayio_group_child_t; - typedef struct { mp_obj_base_t base; - displayio_group_child_t* children; + mp_obj_list_t *members; displayio_buffer_transform_t absolute_transform; displayio_area_t dirty_area; // Catch all for changed area int16_t x; int16_t y; uint16_t scale; - uint16_t size; - uint16_t max_size; - 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, displayio_group_child_t* child_array, uint32_t max_size, 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 cc811e83d7037..6446e3198ffb5 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 4636c3f73a41d..cc5bcf1eb772f 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 c1a0ddeb7e6b5..5c7e00a5839a7 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 28426f11b8744..610b1149105b5 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 ba5ff665c9320..9b6374ac38ba7 100644 --- a/shared-module/displayio/Palette.c +++ b/shared-module/displayio/Palette.c @@ -28,26 +28,30 @@ #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) { +bool common_hal_displayio_palette_is_transparent(displayio_palette_t *self, uint32_t palette_index) { + return self->colors[palette_index].transparent; +} + +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 +65,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 +78,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 993912cc518dc..82504b7ed1788 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 b94a392bc6b81..4a32c7a606968 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 e59ad586e78b9..2cac5d73b24f7 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 19ea10e55299b..a623a10de5506 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; } @@ -74,28 +74,29 @@ void common_hal_displayio_tilegrid_construct(displayio_tilegrid_t *self, mp_obj_ self->flip_x = false; self->flip_y = false; self->transpose_xy = false; + self->absolute_transform = NULL; } -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; } @@ -104,23 +105,30 @@ bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_ } void _update_current_x(displayio_tilegrid_t *self) { - int16_t width; + uint16_t width; if (self->transpose_xy) { width = self->pixel_height; } else { width = self->pixel_width; } - if (self->absolute_transform->transpose_xy) { - self->current_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * self->x; - self->current_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->x + width); + + // 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 + ? &null_transform + : self->absolute_transform; + + if (absolute_transform->transpose_xy) { + self->current_area.y1 = absolute_transform->y + absolute_transform->dy * self->x; + self->current_area.y2 = absolute_transform->y + absolute_transform->dy * (self->x + width); if (self->current_area.y2 < self->current_area.y1) { int16_t temp = self->current_area.y2; self->current_area.y2 = self->current_area.y1; self->current_area.y1 = temp; } } else { - self->current_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * self->x; - self->current_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->x + width); + self->current_area.x1 = absolute_transform->x + absolute_transform->dx * self->x; + self->current_area.x2 = absolute_transform->x + absolute_transform->dx * (self->x + width); if (self->current_area.x2 < self->current_area.x1) { int16_t temp = self->current_area.x2; self->current_area.x2 = self->current_area.x1; @@ -130,23 +138,30 @@ void _update_current_x(displayio_tilegrid_t *self) { } void _update_current_y(displayio_tilegrid_t *self) { - int16_t height; + uint16_t height; if (self->transpose_xy) { height = self->pixel_width; } else { height = self->pixel_height; } - if (self->absolute_transform->transpose_xy) { - self->current_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * self->y; - self->current_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->y + height); + + // 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 + ? &null_transform + : self->absolute_transform; + + if (absolute_transform->transpose_xy) { + self->current_area.x1 = absolute_transform->x + absolute_transform->dx * self->y; + self->current_area.x2 = absolute_transform->x + absolute_transform->dx * (self->y + height); if (self->current_area.x2 < self->current_area.x1) { int16_t temp = self->current_area.x2; self->current_area.x2 = self->current_area.x1; self->current_area.x1 = temp; } } else { - self->current_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * self->y; - self->current_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->y + height); + self->current_area.y1 = absolute_transform->y + absolute_transform->dy * self->y; + self->current_area.y2 = absolute_transform->y + absolute_transform->dy * (self->y + height); if (self->current_area.y2 < self->current_area.y1) { int16_t temp = self->current_area.y2; self->current_area.y2 = self->current_area.y1; @@ -156,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) { @@ -215,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; @@ -229,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 { @@ -258,7 +273,7 @@ void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t tile_area->y2 = tile_area->y1 + self->tile_height; if (self->partial_change) { - displayio_area_expand(&self->dirty_area, &temp_area); + displayio_area_union(&self->dirty_area, &temp_area, &self->dirty_area); } self->partial_change = true; @@ -316,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; @@ -369,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); @@ -428,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; @@ -456,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) { @@ -477,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; } } } @@ -514,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. @@ -538,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. @@ -550,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; @@ -559,16 +574,16 @@ 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; } if (self->partial_change) { - if (self->absolute_transform->transpose_xy) { + if (self->transpose_xy != self->absolute_transform->transpose_xy) { int16_t x1 = self->dirty_area.x1; self->dirty_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * (self->y + self->dirty_area.y1); self->dirty_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * (self->x + x1); diff --git a/shared-module/displayio/TileGrid.h b/shared-module/displayio/TileGrid.h index e97d3dfd47ddb..b5aab51348bab 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 a9bb3b21b6fe3..7d9dc26dd3da6 100644 --- a/shared-module/displayio/__init__.c +++ b/shared-module/displayio/__init__.c @@ -26,11 +26,25 @@ primary_display_t displays[CIRCUITPY_DISPLAY_LIMIT]; +displayio_buffer_transform_t null_transform = { + .x = 0, + .y = 0, + .dx = 1, + .dy = 1, + .scale = 1, + .width = 0, + .height = 0, + .mirror_x = false, + .mirror_y = false, + .transpose_xy = false +}; + + #if CIRCUITPY_RGBMATRIX 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; } @@ -58,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); } @@ -80,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; } @@ -97,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; } @@ -116,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; @@ -190,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; @@ -221,55 +235,40 @@ 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) { - if (addition->x1 < original->x1) { - original->x1 = addition->x1; - } - if (addition->y1 < original->y1) { - original->y1 = addition->y1; - } - if (addition->x2 > original->x2) { - original->x2 = addition->x2; - } - if (addition->y2 > original->y2) { - original->y2 = addition->y2; - } -} - -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; @@ -295,41 +294,61 @@ 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) { - u->x1 = a->x1; - if (b->x1 < u->x1) { - u->x1 = b->x1; +void displayio_copy_coords(const displayio_area_t *src, displayio_area_t *dest) { + dest->x1 = src->x1; + dest->y1 = src->y1; + dest->x2 = src->x2; + dest->y2 = src->y2; +} + +bool displayio_area_empty(const displayio_area_t *a) { + return (a->x1 == a->x2) || (a->y1 == a->y2); +} + +void displayio_area_canon(displayio_area_t *a) { + if (a->x1 > a->x2) { + int16_t t = a->x1; + a->x1 = a->x2; + a->x2 = t; } - u->x2 = a->x2; - if (b->x2 > u->x2) { - u->x2 = b->x2; + if (a->y1 > a->y2) { + int16_t t = a->y1; + a->y1 = a->y2; + a->y2 = t; } +} + +void displayio_area_union(const displayio_area_t *a, + const displayio_area_t *b, + displayio_area_t *u) { - u->y1 = a->y1; - if (b->y1 < u->y1) { - u->y1 = b->y1; + if (displayio_area_empty(a)) { + displayio_copy_coords(b, u); + return; } - u->y2 = a->y2; - if (b->y2 > u->y2) { - u->y2 = b->y2; + if (displayio_area_empty(b)) { + displayio_copy_coords(a, u); + return; } + u->x1 = MIN(a->x1, b->x1); + u->y1 = MIN(a->y1, b->y1); + u->x2 = MAX(a->x2, b->x2); + u->y2 = MAX(a->y2, b->y2); } -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 && @@ -338,9 +357,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 44ad5a9a98ab8..4a74b0e0e0c21 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 ec7c389b4b55a..6a8ad6ceb0381 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 { @@ -51,23 +51,27 @@ typedef struct { bool transpose_xy; } displayio_buffer_transform_t; -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); +extern displayio_buffer_transform_t null_transform; + +bool displayio_area_empty(const displayio_area_t *a); +void displayio_area_copy_coords(const displayio_area_t *src, displayio_area_t *dest); +void displayio_area_canon(displayio_area_t *a); +void displayio_area_union(const displayio_area_t *a, + const displayio_area_t *b, + displayio_area_t *u); +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 57d33b5651a03..a0b3afa0ee948 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 fe6cb6f3f5d28..8c2ba21b5e369 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 58820d5240212..b77a6a1c8b8a7 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 30b4ade8c6a8d..79c8614194e4c 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 03e121c914c7b..e236616f9388e 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 d73d4b9a95a1e..b6138e22029b7 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 7b4108eb2ef1a..55b447f1eb9c2 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 048fbcd2b22f5..7c28e2285b6a7 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 9874b2752986d..c707886065a86 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 51da61702145d..6efa0ea5cf097 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 b4b26b7a98d77..53aef50986b6e 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 47a008c503276..44cf3be8125fe 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 f573d9d0a2faa..6850fcadc016c 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 a8f8e1caf8d92..9d98c0eb7c8bf 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 35f4e4c63669d..473a19396afd7 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 172c24f6c853a..1f6e3d069271c 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 c28e65592c233..42fae3b0659fb 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 3baab2213ef57..3af1a1a3a17f3 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 1030031749a65..61547fde3a150 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 159b54e315746..89c7952671895 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 42499bc0a1a33..95ac3bc659936 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 b8db0d89391a1..a0dc783b554b0 100644 --- a/shared-module/rgbmatrix/RGBMatrix.c +++ b/shared-module/rgbmatrix/RGBMatrix.c @@ -56,7 +56,7 @@ void common_hal_rgbmatrix_rgbmatrix_construct(rgbmatrix_rgbmatrix_obj_t *self, i self->tile = tile; self->serpentine = serpentine; - self->timer = timer ? timer : common_hal_rgbmatrix_timer_allocate(); + self->timer = timer ? timer : common_hal_rgbmatrix_timer_allocate(self); if (self->timer == NULL) { mp_raise_ValueError(translate("No timer available")); } @@ -67,7 +67,9 @@ 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); if (framebuffer) { self->framebuffer = framebuffer; @@ -78,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); @@ -94,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, @@ -118,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; } } @@ -145,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; @@ -181,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) { @@ -196,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/RGBMatrix.h b/shared-module/rgbmatrix/RGBMatrix.h index 4a0e9235e74ef..65bfc9799e9e0 100644 --- a/shared-module/rgbmatrix/RGBMatrix.h +++ b/shared-module/rgbmatrix/RGBMatrix.h @@ -26,6 +26,7 @@ #pragma once +#include "py/obj.h" #include "lib/protomatter/src/core.h" extern const mp_obj_type_t rgbmatrix_RGBMatrix_type; diff --git a/shared-module/rgbmatrix/allocator.h b/shared-module/rgbmatrix/allocator.h index 3431046d5b02d..5c11ad52a77fd 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/rotaryio/IncrementalEncoder.c b/shared-module/rotaryio/IncrementalEncoder.c new file mode 100644 index 0000000000000..330895606ef9e --- /dev/null +++ b/shared-module/rotaryio/IncrementalEncoder.c @@ -0,0 +1,86 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#if CIRCUITPY_ROTARYIO && CIRCUITPY_ROTARYIO_SOFTENCODER +#include "shared-module/rotaryio/IncrementalEncoder.h" +#include "common-hal/rotaryio/IncrementalEncoder.h" + +void shared_module_softencoder_state_init(rotaryio_incrementalencoder_obj_t *self, uint8_t quiescent_state) { + self->state = quiescent_state; + self->quarter_count = 0; + common_hal_rotaryio_incrementalencoder_set_position(self, 0); +} + +void shared_module_softencoder_state_update(rotaryio_incrementalencoder_obj_t *self, uint8_t new_state) { + #define BAD 7 + static const int8_t transitions[16] = { + 0, // 00 -> 00 no movement + -1, // 00 -> 01 3/4 ccw (11 detent) or 1/4 ccw (00 at detent) + +1, // 00 -> 10 3/4 cw or 1/4 cw + BAD, // 00 -> 11 non-Gray-code transition + +1, // 01 -> 00 2/4 or 4/4 cw + 0, // 01 -> 01 no movement + BAD, // 01 -> 10 non-Gray-code transition + -1, // 01 -> 11 4/4 or 2/4 ccw + -1, // 10 -> 00 2/4 or 4/4 ccw + BAD, // 10 -> 01 non-Gray-code transition + 0, // 10 -> 10 no movement + +1, // 10 -> 11 4/4 or 2/4 cw + BAD, // 11 -> 00 non-Gray-code transition + +1, // 11 -> 01 1/4 or 3/4 cw + -1, // 11 -> 10 1/4 or 3/4 ccw + 0, // 11 -> 11 no movement + }; + + new_state &= 0x3; + int idx = (self->state << 2) | new_state; + self->state = new_state; + + int8_t quarter_incr = transitions[idx]; + if (quarter_incr == BAD) { + // Missed a transition. We don't know which way we're going, so do nothing. + return; + } + + self->quarter_count += quarter_incr; + + if (self->quarter_count >= 4) { + self->position += 1; + self->quarter_count = 0; + } else if (self->quarter_count <= -4) { + self->position -= 1; + self->quarter_count = 0; + } +} + +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 position) { + self->position = position; +} +#endif diff --git a/shared-module/rotaryio/IncrementalEncoder.h b/shared-module/rotaryio/IncrementalEncoder.h new file mode 100644 index 0000000000000..82a5644b470f6 --- /dev/null +++ b/shared-module/rotaryio/IncrementalEncoder.h @@ -0,0 +1,34 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Jeff Epler for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#pragma once + +#include "common-hal/rotaryio/IncrementalEncoder.h" + +void shared_module_softencoder_state_init(rotaryio_incrementalencoder_obj_t *self, uint8_t quiescent_state); +void shared_module_softencoder_state_update(rotaryio_incrementalencoder_obj_t *self, uint8_t new_state); +mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self); +void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, mp_int_t position); diff --git a/shared-module/sdcardio/SDCard.c b/shared-module/sdcardio/SDCard.c index 1712f58ee4432..c3263fa0dce54 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 4b92bd637ac96..14f490822295f 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 08966a89c1f35..47e1a373fd623 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 5864307fd54a1..c3de03e7b0d2d 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)); } @@ -149,7 +149,7 @@ void common_hal_storage_remount(const char *mount_path, bool readonly, bool disa mp_raise_OSError(MP_EINVAL); } - #ifdef USB_AVAILABLE + #if CIRCUITPY_USB_MSC if (!usb_msc_ejected()) { mp_raise_RuntimeError(translate("Cannot remount '/' when USB is active.")); } @@ -160,7 +160,9 @@ void common_hal_storage_remount(const char *mount_path, bool readonly, bool disa } void common_hal_storage_erase_filesystem(void) { + #if CIRCUITPY_USB usb_disconnect(); + #endif mp_hal_delay_ms(1000); filesystem_init(false, true); // Force a re-format. common_hal_mcu_reset(); diff --git a/shared-module/struct/__init__.c b/shared-module/struct/__init__.c index 245dbbda97ca8..258036c93b50b 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); @@ -153,9 +153,11 @@ void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte* end_p, size p += sz; } else { while (sz--) { - mp_binary_set_val(fmt_type, *fmt, args[i], &p); // Pad bytes don't have a corresponding argument. - if (*fmt != 'x') { + if (*fmt == 'x') { + mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p); + } else { + mp_binary_set_val(fmt_type, *fmt, args[i], &p); i++; } } @@ -164,50 +166,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) { - - 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")); - } - } - - for (uint i = 0; i < num_items;) { - mp_uint_t sz = 1; - - 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; +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)); + + // 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; + + 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; } diff --git a/shared-module/synthio/MidiTrack.c b/shared-module/synthio/MidiTrack.c new file mode 100644 index 0000000000000..0827945ab59b5 --- /dev/null +++ b/shared-module/synthio/MidiTrack.c @@ -0,0 +1,212 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/runtime.h" +#include "shared-bindings/synthio/MidiTrack.h" + +#define LOUDNESS 0x4000 // 0.5 +#define BITS_PER_SAMPLE 16 +#define BYTES_PER_SAMPLE (BITS_PER_SAMPLE / 8) +#define SILENCE 0x80 + +STATIC uint8_t parse_note(const uint8_t *buffer, uint32_t len, uint32_t *pos) { + if (*pos + 1 >= len) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), *pos); + } + uint8_t note = buffer[(*pos)++]; + if (note > 127 || buffer[(*pos)++] > 127) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), *pos); + } + return note; +} + +STATIC void terminate_span(synthio_miditrack_obj_t *self, uint16_t *dur, uint16_t *max_dur) { + if (*dur) { + self->track[self->total_spans - 1].dur = *dur; + if (*dur > *max_dur) { + *max_dur = *dur; + } + *dur = 0; + } else { + self->total_spans--; + } +} + +STATIC void add_span(synthio_miditrack_obj_t *self, uint8_t note1, uint8_t note2) { + synthio_midi_span_t span = { 0, {note1, note2} }; + self->track = m_realloc(self->track, + (self->total_spans + 1) * sizeof(synthio_midi_span_t)); + self->track[self->total_spans++] = span; +} + +void common_hal_synthio_miditrack_construct(synthio_miditrack_obj_t *self, + const uint8_t *buffer, uint32_t len, uint32_t tempo, uint32_t sample_rate) { + + synthio_midi_span_t initial = { 0, {SILENCE, SILENCE} }; + self->sample_rate = sample_rate; + self->track = m_malloc(sizeof(synthio_midi_span_t), false); + self->next_span = 0; + self->total_spans = 1; + *self->track = initial; + + uint16_t dur = 0, max_dur = 0; + uint32_t pos = 0; + while (pos < len) { + uint8_t c; + uint32_t delta = 0; + do { + c = buffer[pos++]; + delta <<= 7; + delta |= c & 0x7f; + } while ((c & 0x80) && (pos < len)); + + if (c & 0x80) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), pos); + } + + dur += delta * sample_rate / tempo; + + switch (buffer[pos++] >> 4) { + case 8: { // Note Off + uint8_t note = parse_note(buffer, len, &pos); + + // Ignore if not a note which is playing + synthio_midi_span_t last_span = self->track[self->total_spans - 1]; + if (last_span.note[0] == note || last_span.note[1] == note) { + terminate_span(self, &dur, &max_dur); + if (last_span.note[0] == note) { + add_span(self, last_span.note[1], SILENCE); + } else { + add_span(self, last_span.note[0], SILENCE); + } + } + break; + } + case 9: { // Note On + uint8_t note = parse_note(buffer, len, &pos); + + // Ignore if two notes are already playing + synthio_midi_span_t last_span = self->track[self->total_spans - 1]; + if (last_span.note[1] == SILENCE) { + terminate_span(self, &dur, &max_dur); + if (last_span.note[0] == SILENCE) { + add_span(self, note, SILENCE); + } else { + add_span(self, last_span.note[0], note); + } + } + break; + } + case 10: + case 11: + case 14: // two data bytes to ignore + parse_note(buffer, len, &pos); + break; + case 12: + case 13: // one data byte to ignore + if (pos >= len || buffer[pos++] > 127) { + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), pos); + } + break; + case 15: // the full syntax is too complicated, just assume it's "End of Track" event + pos = len; + break; + default: // invalid event + mp_raise_ValueError_varg(translate("Error in MIDI stream at position %d"), pos); + } + } + terminate_span(self, &dur, &max_dur); + + self->buffer_length = max_dur * BYTES_PER_SAMPLE; + self->buffer = m_malloc(self->buffer_length, false); +} + +void common_hal_synthio_miditrack_deinit(synthio_miditrack_obj_t *self) { + m_free(self->buffer); + self->buffer = NULL; + m_free(self->track); + self->track = NULL; +} +bool common_hal_synthio_miditrack_deinited(synthio_miditrack_obj_t *self) { + return self->buffer == NULL; +} + +uint32_t common_hal_synthio_miditrack_get_sample_rate(synthio_miditrack_obj_t *self) { + return self->sample_rate; +} +uint8_t common_hal_synthio_miditrack_get_bits_per_sample(synthio_miditrack_obj_t *self) { + return BITS_PER_SAMPLE; +} +uint8_t common_hal_synthio_miditrack_get_channel_count(synthio_miditrack_obj_t *self) { + return 1; +} + +void synthio_miditrack_reset_buffer(synthio_miditrack_obj_t *self, + bool single_channel, uint8_t channel) { + + self->next_span = 0; +} + +STATIC const uint16_t notes[] = {8372, 8870, 9397, 9956, 10548, 11175, 11840, + 12544, 13290, 14080, 14917, 15804}; // 9th octave + +audioio_get_buffer_result_t synthio_miditrack_get_buffer(synthio_miditrack_obj_t *self, + bool single_channel, uint8_t channel, uint8_t **buffer, uint32_t *buffer_length) { + + if (self->next_span >= self->total_spans) { + *buffer_length = 0; + return GET_BUFFER_DONE; + } + + synthio_midi_span_t span = self->track[self->next_span++]; + *buffer_length = span.dur * BYTES_PER_SAMPLE; + uint8_t octave1 = span.note[0] / 12; // 0..10 + uint8_t octave2 = span.note[1] / 12; // 0..10 + int32_t base_freq1 = notes[span.note[0] % 12]; + int32_t base_freq2 = notes[span.note[1] % 12]; + int32_t sample_rate = self->sample_rate; + + for (uint16_t i = 0; i < span.dur; i++) { + int16_t semiperiod1 = span.note[0] == SILENCE ? 0 : + ((base_freq1 * i * 2) / sample_rate) >> (10 - octave1); + int16_t semiperiod2 = span.note[1] == SILENCE ? semiperiod1 : + ((base_freq2 * i * 2) / sample_rate) >> (10 - octave2); + self->buffer[i] = ((semiperiod1 % 2 + semiperiod2 % 2) - 1) * LOUDNESS; + } + *buffer = (uint8_t *)self->buffer; + + return self->next_span >= self->total_spans ? + GET_BUFFER_DONE : GET_BUFFER_MORE_DATA; +} + +void synthio_miditrack_get_buffer_structure(synthio_miditrack_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 = true; + *max_buffer_length = self->buffer_length; + *spacing = 1; +} diff --git a/shared-module/synthio/MidiTrack.h b/shared-module/synthio/MidiTrack.h new file mode 100644 index 0000000000000..bd058daaee564 --- /dev/null +++ b/shared-module/synthio/MidiTrack.h @@ -0,0 +1,65 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO_MIDITRACK_H +#define MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO_MIDITRACK_H + +#include "py/obj.h" + +#include "shared-module/synthio/__init__.h" + +typedef struct { + uint16_t dur; + uint8_t note[2]; +} synthio_midi_span_t; + +typedef struct { + mp_obj_base_t base; + uint32_t sample_rate; + uint16_t *buffer; + uint16_t buffer_length; + synthio_midi_span_t *track; + uint16_t next_span; + uint16_t total_spans; +} synthio_miditrack_obj_t; + + +// These are not available from Python because it may be called in an interrupt. +void synthio_miditrack_reset_buffer(synthio_miditrack_obj_t *self, + bool single_channel, + uint8_t channel); + +audioio_get_buffer_result_t synthio_miditrack_get_buffer(synthio_miditrack_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes + +void synthio_miditrack_get_buffer_structure(synthio_miditrack_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_SYNTHIO_MIDITRACK_H diff --git a/shared-module/synthio/__init__.c b/shared-module/synthio/__init__.c new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/shared-module/synthio/__init__.h b/shared-module/synthio/__init__.h new file mode 100644 index 0000000000000..d9d98a5341665 --- /dev/null +++ b/shared-module/synthio/__init__.h @@ -0,0 +1,32 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Artyom Skrobov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO__INIT__H +#define MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO__INIT__H + +#include "shared-module/audiocore/__init__.h" + +#endif // MICROPY_INCLUDED_SHARED_MODULE_SYNTHIO__INIT__H diff --git a/shared-module/terminalio/Terminal.c b/shared-module/terminalio/Terminal.c index df92a5dc48688..8ef2acd1caebe 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--; @@ -93,6 +93,41 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con self->cursor_x -= n; } } + if (c == 'J') { + if (n == 2) { + common_hal_displayio_tilegrid_set_top_left(self->tilegrid, 0, 0); + self->cursor_x = self->cursor_y = start_y = 0; + n = 0; + for (uint16_t x = 0; x < self->tilegrid->width_in_tiles; x++) { + for (uint16_t y = 0; y < self->tilegrid->height_in_tiles; y++) { + common_hal_displayio_tilegrid_set_tile(self->tilegrid, x, y, 0); + } + } + } + } + if (c == ';') { + int16_t m = 0; + for (++j; j < 9; j++) { + if ('0' <= i[j] && i[j] <= '9') { + m = m * 10 + (i[j] - '0'); + } else { + c = i[j]; + break; + } + } + if (c == 'H') { + if (n >= self->tilegrid->height_in_tiles) { + n = self->tilegrid->height_in_tiles - 1; + } + if (m >= self->tilegrid->width_in_tiles) { + m = self->tilegrid->width_in_tiles - 1; + } + n = (n + self->tilegrid->top_left_y) % self->tilegrid->height_in_tiles; + self->cursor_x = m; + self->cursor_y = n; + start_y = self->cursor_y; + } + } i += j + 1; continue; } @@ -114,12 +149,14 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con self->cursor_y %= self->tilegrid->height_in_tiles; } if (self->cursor_y != start_y) { - // clear the new row - for (uint16_t j = 0; j < self->tilegrid->width_in_tiles; j++) { - common_hal_displayio_tilegrid_set_tile(self->tilegrid, j, self->cursor_y, 0); - start_y = self->cursor_y; + // clear the new row in case of scroll up + if (self->cursor_y == self->tilegrid->top_left_y) { + for (uint16_t j = 0; j < self->tilegrid->width_in_tiles; j++) { + common_hal_displayio_tilegrid_set_tile(self->tilegrid, j, self->cursor_y, 0); + } + common_hal_displayio_tilegrid_set_top_left(self->tilegrid, 0, (self->cursor_y + self->tilegrid->height_in_tiles + 1) % self->tilegrid->height_in_tiles); } - common_hal_displayio_tilegrid_set_top_left(self->tilegrid, 0, (start_y + self->tilegrid->height_in_tiles + 1) % self->tilegrid->height_in_tiles); + start_y = self->cursor_y; } } return i - data; diff --git a/shared-module/terminalio/Terminal.h b/shared-module/terminalio/Terminal.h index c31392cc4ff4d..2ba7e21f72295 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 3fdf3e0ca1fd8..840c14571d120 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 5ef15dce42236..fd8e31ec0ddc0 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/Serial.c b/shared-module/usb_cdc/Serial.c new file mode 100644 index 0000000000000..b4d8667ca67c2 --- /dev/null +++ b/shared-module/usb_cdc/Serial.c @@ -0,0 +1,149 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dan Halbert for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "lib/utils/interrupt_char.h" +#include "shared-module/usb_cdc/Serial.h" +#include "supervisor/shared/tick.h" + +#include "tusb.h" + +size_t common_hal_usb_cdc_serial_read(usb_cdc_serial_obj_t *self, uint8_t *data, size_t len, int *errcode) { + + const bool wait_forever = self->timeout < 0.0f; + const bool wait_for_timeout = self->timeout > 0.0f; + + // Read up to len bytes immediately. + // The number of bytes read will not be larger than what is already in the TinyUSB FIFO. + uint32_t total_num_read = tud_cdc_n_read(self->idx, data, len); + + if (wait_forever || wait_for_timeout) { + // Read more if we have time. + // Use special routine to avoid pulling in uint64-float-compatible math routines. + uint64_t timeout_ms = float_to_uint64(self->timeout * 1000); // Junk value if timeout < 0. + uint64_t start_ticks = supervisor_ticks_ms64(); + + uint32_t num_read = 0; + while (total_num_read < len && + (wait_forever || supervisor_ticks_ms64() - start_ticks <= timeout_ms)) { + + // Wait for a bit, and check for ctrl-C. + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + return 0; + } + + // Advance buffer pointer and reduce number of bytes that need to be read. + len -= num_read; + data += num_read; + + // Try to read another batch of bytes. + num_read = tud_cdc_n_read(self->idx, data, len); + total_num_read += num_read; + } + } + + return total_num_read; +} + +size_t common_hal_usb_cdc_serial_write(usb_cdc_serial_obj_t *self, const uint8_t *data, size_t len, int *errcode) { + const bool wait_forever = self->write_timeout < 0.0f; + const bool wait_for_timeout = self->write_timeout > 0.0f; + + // Write as many bytes as possible immediately. + // The number of bytes written at once will not be larger than what can fit in the TinyUSB FIFO. + uint32_t total_num_written = tud_cdc_n_write(self->idx, data, len); + tud_cdc_n_write_flush(self->idx); + + if (wait_forever || wait_for_timeout) { + // Write more if we have time. + // Use special routine to avoid pulling in uint64-float-compatible math routines. + uint64_t timeout_ms = float_to_uint64(self->write_timeout * 1000); // Junk value if write_timeout < 0. + uint64_t start_ticks = supervisor_ticks_ms64(); + + uint32_t num_written = 0; + while (total_num_written < len && + (wait_forever || supervisor_ticks_ms64() - start_ticks <= timeout_ms)) { + + // Wait for a bit, and check for ctrl-C. + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + return 0; + } + + // Advance buffer pointer and reduce number of bytes that need to be written. + len -= num_written; + data += num_written; + + // Try to write another batch of bytes. + num_written = tud_cdc_n_write(self->idx, data, len); + tud_cdc_n_write_flush(self->idx); + total_num_written += num_written; + } + } + + return total_num_written; +} + +uint32_t common_hal_usb_cdc_serial_get_in_waiting(usb_cdc_serial_obj_t *self) { + return tud_cdc_n_available(self->idx); +} + +uint32_t common_hal_usb_cdc_serial_get_out_waiting(usb_cdc_serial_obj_t *self) { + // Return number of FIFO bytes currently occupied. + return CFG_TUD_CDC_TX_BUFSIZE - tud_cdc_n_write_available(self->idx); +} + +void common_hal_usb_cdc_serial_reset_input_buffer(usb_cdc_serial_obj_t *self) { + tud_cdc_n_read_flush(self->idx); +} + +uint32_t common_hal_usb_cdc_serial_reset_output_buffer(usb_cdc_serial_obj_t *self) { + return tud_cdc_n_write_clear(self->idx); +} + +uint32_t common_hal_usb_cdc_serial_flush(usb_cdc_serial_obj_t *self) { + return tud_cdc_n_write_flush(self->idx); +} + +bool common_hal_usb_cdc_serial_get_connected(usb_cdc_serial_obj_t *self) { + return tud_cdc_n_connected(self->idx); +} + +mp_float_t common_hal_usb_cdc_serial_get_timeout(usb_cdc_serial_obj_t *self) { + return self->timeout; +} + +void common_hal_usb_cdc_serial_set_timeout(usb_cdc_serial_obj_t *self, mp_float_t timeout) { + self->timeout = timeout; +} + +mp_float_t common_hal_usb_cdc_serial_get_write_timeout(usb_cdc_serial_obj_t *self) { + return self->write_timeout; +} + +void common_hal_usb_cdc_serial_set_write_timeout(usb_cdc_serial_obj_t *self, mp_float_t write_timeout) { + self->write_timeout = write_timeout; +} diff --git a/shared-module/usb_cdc/Serial.h b/shared-module/usb_cdc/Serial.h new file mode 100644 index 0000000000000..ddf78eefa63eb --- /dev/null +++ b/shared-module/usb_cdc/Serial.h @@ -0,0 +1,39 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dan Halbert for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef SHARED_MODULE_USB_CDC_SERIAL_H +#define SHARED_MODULE_USB_CDC_SERIAL_H + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + mp_float_t timeout; // if negative, wait forever. + mp_float_t write_timeout; // if negative, wait forever. + uint8_t idx; // which CDC device? +} usb_cdc_serial_obj_t; + +#endif // SHARED_MODULE_USB_CDC_SERIAL_H diff --git a/drivers/bus/spi.h b/shared-module/usb_cdc/__init__.c similarity index 58% rename from drivers/bus/spi.h rename to shared-module/usb_cdc/__init__.c index 5d150cd38f048..3cf80a8b5c2c0 100644 --- a/drivers/bus/spi.h +++ b/shared-module/usb_cdc/__init__.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * SPDX-FileCopyrightText: Copyright (c) 2016-2018 Damien P. George + * Copyright (c) 2021 Dan Halbert for Adafruit Industries * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,33 +23,38 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_DRIVERS_BUS_SPI_H -#define MICROPY_INCLUDED_DRIVERS_BUS_SPI_H +#include "genhdr/autogen_usb_descriptor.h" +#include "py/gc.h" +#include "py/obj.h" #include "py/mphal.h" +#include "py/runtime.h" +#include "py/objtuple.h" +#include "shared-bindings/usb_cdc/__init__.h" +#include "shared-bindings/usb_cdc/Serial.h" +#include "tusb.h" -enum { - MP_SPI_IOCTL_INIT, - MP_SPI_IOCTL_DEINIT, -}; - -typedef struct _mp_spi_proto_t { - int (*ioctl)(void *self, uint32_t cmd); - void (*transfer)(void *self, size_t len, const uint8_t *src, uint8_t *dest); -} mp_spi_proto_t; - -typedef struct _mp_soft_spi_obj_t { - uint32_t delay_half; // microsecond delay for half SCK period - uint8_t polarity; - uint8_t phase; - mp_hal_pin_obj_t sck; - mp_hal_pin_obj_t mosi; - mp_hal_pin_obj_t miso; -} mp_soft_spi_obj_t; +#if CFG_TUD_CDC != 2 +#error CFG_TUD_CDC must be exactly 2 +#endif -extern const mp_spi_proto_t mp_soft_spi_proto; - -int mp_soft_spi_ioctl(void *self, uint32_t cmd); -void mp_soft_spi_transfer(void *self, size_t len, const uint8_t *src, uint8_t *dest); +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,}, { + .base.type = &usb_cdc_serial_type, + .timeout = -1.0f, + .write_timeout = -1.0f, + .idx = 1, + } +}; -#endif // MICROPY_INCLUDED_DRIVERS_BUS_SPI_H +const mp_rom_obj_tuple_t usb_cdc_serials_tuple = { + .base.type = &mp_type_tuple, + .len = CFG_TUD_CDC, + .items = { + &serial_objs[0], + &serial_objs[1], + }, +}; diff --git a/shared-module/usb_cdc/__init__.h b/shared-module/usb_cdc/__init__.h new file mode 100644 index 0000000000000..9de3eb2faab9e --- /dev/null +++ b/shared-module/usb_cdc/__init__.h @@ -0,0 +1,34 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Dan Halbert for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef SHARED_MODULE_USB_CDC___INIT___H +#define SHARED_MODULE_USB_CDC___INIT___H + +#include "py/objtuple.h" + +extern const mp_rom_obj_tuple_t usb_cdc_serials_tuple; + +#endif /* SHARED_MODULE_USB_CDC___INIT___H */ diff --git a/shared-module/usb_hid/Device.c b/shared-module/usb_hid/Device.c index 943c9bfed791a..4f392847ffc82 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,9 +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 report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) { +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); @@ -83,7 +86,8 @@ uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, } // Callbacks invoked when receive Set_Report request through control endpoint -void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) { +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++; @@ -92,7 +96,7 @@ void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uin 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 93c3518b4374f..bf4e9d9adb743 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/PortIn.c b/shared-module/usb_midi/PortIn.c index 31e320baab753..e00a5124cfe0e 100644 --- a/shared-module/usb_midi/PortIn.c +++ b/shared-module/usb_midi/PortIn.c @@ -29,7 +29,7 @@ #include "tusb.h" size_t common_hal_usb_midi_portin_read(usb_midi_portin_obj_t *self, uint8_t *data, size_t len, int *errcode) { - return tud_midi_read(data, len); + return tud_midi_stream_read(data, len); } uint32_t common_hal_usb_midi_portin_bytes_available(usb_midi_portin_obj_t *self) { diff --git a/shared-module/usb_midi/PortOut.c b/shared-module/usb_midi/PortOut.c index 0b37dcfd41b72..f453a67671e3d 100644 --- a/shared-module/usb_midi/PortOut.c +++ b/shared-module/usb_midi/PortOut.c @@ -29,7 +29,7 @@ #include "tusb.h" size_t common_hal_usb_midi_portout_write(usb_midi_portout_obj_t *self, const uint8_t *data, size_t len, int *errcode) { - return tud_midi_write(0, data, len); + return tud_midi_stream_write(0, data, len); } bool common_hal_usb_midi_portout_ready_to_tx(usb_midi_portout_obj_t *self) { diff --git a/shared-module/usb_midi/__init__.c b/shared-module/usb_midi/__init__.c index 3fb3f836cd763..0684112b72656 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 1e168ad6a0632..55e5fa2d1a7e0 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 73629b8ceeb5e..9c7458065036a 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 e00a4696b26bb..00af1e0d7ead3 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/Rectangle.c b/shared-module/vectorio/Rectangle.c index 5d48cc648095c..56be5ebb5e6a1 100644 --- a/shared-module/vectorio/Rectangle.c +++ b/shared-module/vectorio/Rectangle.c @@ -12,7 +12,7 @@ void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_ uint32_t common_hal_vectorio_rectangle_get_pixel(void *obj, int16_t x, int16_t y) { vectorio_rectangle_t *self = obj; - if (x < 0 || x > self->width || y > self->height || y < 0) { + if (x < 0 || x >= self->width || y >= self->height || y < 0) { return 0; } return 1; @@ -21,8 +21,8 @@ uint32_t common_hal_vectorio_rectangle_get_pixel(void *obj, int16_t x, int16_t y void common_hal_vectorio_rectangle_get_area(void *rectangle, displayio_area_t *out_area) { vectorio_rectangle_t *self = rectangle; - out_area->x1 = -1; - out_area->y1 = -1; + out_area->x1 = 0; + out_area->y1 = 0; out_area->x2 = self->width; out_area->y2 = self->height; } diff --git a/shared-module/vectorio/VectorShape.c b/shared-module/vectorio/VectorShape.c index 81f46b3fa03bb..efc40d0356bf0 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; @@ -55,16 +55,7 @@ static void _get_screen_area(vectorio_vector_shape_t *self, displayio_area_t *ou out_area->y2 = (out_area->y2 + self->y) * self->absolute_transform->dy + self->absolute_transform->y; } // We might have mirrored due to dx - if (out_area->x2 < out_area->x1) { - int16_t swap = out_area->x1; - out_area->x1 = out_area->x2; - out_area->x2 = swap; - } - if (out_area->y2 < out_area->y1) { - int16_t swap = out_area->y1; - out_area->y1 = out_area->y2; - out_area->y2 = swap; - } + displayio_area_canon(out_area); VECTORIO_SHAPE_DEBUG(" out:{(%5d,%5d), (%5d,%5d)}\n", out_area->x1, out_area->y1, out_area->x2, out_area->y2); } @@ -88,28 +79,14 @@ void common_hal_vectorio_vector_shape_set_dirty(void *vector_shape) { self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2); self->dirty = true; // Dirty area tracks the shape's footprint between draws. It's reset on refresh finish, - displayio_area_expand(&self->ephemeral_dirty_area, ¤t_area); + displayio_area_union(&self->ephemeral_dirty_area, ¤t_area, &self->ephemeral_dirty_area); VECTORIO_SHAPE_DEBUG(" -> expanded:{(%3d,%3d), (%3d,%3d)}\n", self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2); } -static displayio_buffer_transform_t null_transform = { - .x = 0, - .y = 0, - .dx = 1, - .dy = 1, - .scale = 1, - .width = 0, - .height = 0, - .mirror_x = false, - .mirror_y = false, - .transpose_xy = false -}; - - 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; @@ -166,22 +143,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; @@ -208,7 +185,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"); @@ -227,14 +204,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; @@ -252,10 +229,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) { @@ -270,13 +247,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", @@ -286,15 +263,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); @@ -313,7 +290,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 56eb3d8a5363c..1896c72d6e660 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 8ccb4ff8d2b95..708d2166e614d 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/flash.h b/supervisor/flash.h index cd69cbfa9bf87..21d76c9984746 100644 --- a/supervisor/flash.h +++ b/supervisor/flash.h @@ -31,10 +31,10 @@ #include "py/mpconfig.h" -#ifdef EXTERNAL_FLASH_DEVICE_COUNT -#include "supervisor/shared/external_flash/external_flash.h" -#else +#if INTERNAL_FLASH_FILESYSTEM #include "supervisor/shared/internal_flash.h" +#else +#include "supervisor/shared/external_flash/external_flash.h" #endif void supervisor_flash_init(void); diff --git a/supervisor/flash_root_pointers.h b/supervisor/flash_root_pointers.h index 634ae58d3fbba..a426b9c4eb01d 100644 --- a/supervisor/flash_root_pointers.h +++ b/supervisor/flash_root_pointers.h @@ -26,7 +26,7 @@ #ifndef MICROPY_INCLUDED_SUPERVISOR_FLASH_ROOT_POINTERS_H #define MICROPY_INCLUDED_SUPERVISOR_FLASH_ROOT_POINTERS_H -#ifdef EXTERNAL_FLASH_DEVICE_COUNT +#ifdef EXTERNAL_FLASH_DEVICES #include "supervisor/shared/external_flash/external_flash_root_pointers.h" #else #include "supervisor/internal_flash_root_pointers.h" diff --git a/supervisor/linker.h b/supervisor/linker.h old mode 100755 new mode 100644 index 74b2dd5a6d21d..58068c1a4b724 --- a/supervisor/linker.h +++ b/supervisor/linker.h @@ -29,10 +29,10 @@ #ifndef MICROPY_INCLUDED_SUPERVISOR_LINKER_H #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 +#if defined(IMXRT10XX) || defined(FOMU) || defined(STM32H7) || defined(RASPBERRYPI) +#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 0f820eac1c475..0aa38eec376d8 --- 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 812cf715b1913..0a8cdfd34248e 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 066886303e920..e85231c6c712e 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 288c9a4df297a..0dafb5398d145 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 *callback_head, *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,10 +48,9 @@ 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; - cb->prev = (background_callback_t*)callback_tail; } if (!callback_head) { callback_head = cb; @@ -78,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) { @@ -108,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; @@ -135,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 56bf321173ec6..00095c4f6b339 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 6d648510e715f..427c179242942 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 fe887a933545e..def5f48655622 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/cpu.c b/supervisor/shared/cpu.c new file mode 100644 index 0000000000000..510225d197d87 --- /dev/null +++ b/supervisor/shared/cpu.c @@ -0,0 +1,40 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "supervisor/shared/cpu.h" + +bool cpu_interrupt_active(void) { + #if defined(__ARM_ARCH) && (__ARM_ARCH >= 6) + // Check VECTACTIVE in ICSR. We don't need to disable interrupts because if + // one occurs after we read, we won't continue until it is resolved. + return (*((volatile uint32_t *)0xE000ED04) & 0x1ff) != 0; + #else + // We don't know. + return false; + #endif +} diff --git a/supervisor/shared/cpu.h b/supervisor/shared/cpu.h new file mode 100644 index 0000000000000..9e2bed1e5552f --- /dev/null +++ b/supervisor/shared/cpu.h @@ -0,0 +1,36 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 Scott Shawcroft for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_CPU_H +#define MICROPY_INCLUDED_SUPERVISOR_SHARED_CPU_H + +#include +#include + +// True when we're in an interrupt handler. +bool cpu_interrupt_active(void); + +#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_CPU_H diff --git a/supervisor/shared/display.c b/supervisor/shared/display.c index 9c9c66cd7fb69..6ee6c7386a9e6 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 @@ -270,15 +270,20 @@ displayio_tilegrid_t blinka_sprite = { }; #if CIRCUITPY_TERMINALIO -#define CHILD_COUNT 2 -displayio_group_child_t splash_children[2] = { - {&blinka_sprite, &blinka_sprite}, - {&supervisor_terminal_text_grid, &supervisor_terminal_text_grid} +mp_obj_t members[] = { &blinka_sprite, &supervisor_terminal_text_grid, }; +mp_obj_list_t splash_children = { + .base = {.type = &mp_type_list }, + .alloc = 2, + .len = 2, + .items = members, }; #else -#define CHILD_COUNT 1 -displayio_group_child_t splash_children[1] = { - {&blinka_sprite, &blinka_sprite}, +mp_obj_t members[] = { &blinka_sprite }; +mp_obj_list_t splash_children = { + .base = {.type = &mp_type_list }, + .alloc = 1, + .len = 1, + .items = members, }; #endif @@ -287,9 +292,7 @@ displayio_group_t circuitpython_splash = { .x = 0, .y = 0, .scale = 2, - .size = CHILD_COUNT, - .max_size = CHILD_COUNT, - .children = splash_children, + .members = &splash_children, .item_removed = false, .in_group = false, .hidden = false, diff --git a/supervisor/shared/external_flash/device.h b/supervisor/shared/external_flash/device.h new file mode 100644 index 0000000000000..bbf6bfd91b64b --- /dev/null +++ b/supervisor/shared/external_flash/device.h @@ -0,0 +1,78 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICE_H +#define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICE_H + +#include +#include + +typedef struct { + uint32_t total_size; + uint16_t start_up_time_us; + + // Three response bytes to 0x9f JEDEC ID command. + uint8_t manufacturer_id; + uint8_t memory_type; + uint8_t capacity; + + // Max clock speed for all operations and the fastest read mode. + uint8_t max_clock_speed_mhz; + + // Bitmask for Quad Enable bit if present. 0x00 otherwise. This is for the highest byte in the + // status register. + uint8_t quad_enable_bit_mask; + + bool has_sector_protection : 1; + + // Supports the 0x0b fast read command with 8 dummy cycles. + bool supports_fast_read : 1; + + // Supports the fast read, quad output command 0x6b with 8 dummy cycles. + bool supports_qspi : 1; + + // 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; + + // 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; + + // 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; + + // Does not support using a ready bit within the status register + bool no_ready_bit : 1; + + // Does not support the erase command (0x20) + bool no_erase_cmd : 1; + + // Device does not have a reset command + bool no_reset_cmd : 1; +} external_flash_device; + +#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICE_H diff --git a/supervisor/shared/external_flash/devices.h b/supervisor/shared/external_flash/devices.h deleted file mode 100644 index c8c941adf857c..0000000000000 --- a/supervisor/shared/external_flash/devices.h +++ /dev/null @@ -1,716 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -#ifndef MICROPY_INCLUDED_ATMEL_SAMD_EXTERNAL_FLASH_DEVICES_H -#define MICROPY_INCLUDED_ATMEL_SAMD_EXTERNAL_FLASH_DEVICES_H - -#include -#include - -typedef struct { - uint32_t total_size; - uint16_t start_up_time_us; - - // Three response bytes to 0x9f JEDEC ID command. - uint8_t manufacturer_id; - uint8_t memory_type; - uint8_t capacity; - - // Max clock speed for all operations and the fastest read mode. - uint8_t max_clock_speed_mhz; - - // Bitmask for Quad Enable bit if present. 0x00 otherwise. This is for the highest byte in the - // status register. - uint8_t quad_enable_bit_mask; - - bool has_sector_protection : 1; - - // Supports the 0x0b fast read command with 8 dummy cycles. - bool supports_fast_read : 1; - - // Supports the fast read, quad output command 0x6b with 8 dummy cycles. - bool supports_qspi : 1; - - // 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; - - // 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; - - // 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; - - // Does not support using a ready bit within the status register - bool no_ready_bit: 1; - - // Does not support the erase command (0x20) - bool no_erase_cmd: 1; - - // Device does not have a reset command - 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, \ -} - -// 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, \ -} - -// 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, \ -} - - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ - } - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} - -// 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, \ -} -#endif // MICROPY_INCLUDED_ATMEL_SAMD_EXTERNAL_FLASH_DEVICES_H diff --git a/supervisor/shared/external_flash/devices.h.jinja b/supervisor/shared/external_flash/devices.h.jinja new file mode 100644 index 0000000000000..b200b75dcae03 --- /dev/null +++ b/supervisor/shared/external_flash/devices.h.jinja @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICES_H +#define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICES_H + +{% for device in nvms %} +#define {{ device.sku }} { \ + .total_size = {{ device.total_size }}, \ + .start_up_time_us = {{ device.start_up_time_us }}, \ + .manufacturer_id = {{ device.manufacturer_id }}, \ + .memory_type = {{ device.memory_type }}, \ + .capacity = {{ device.capacity }}, \ + .max_clock_speed_mhz = {{ device.max_clock_speed_mhz }}, \ + .quad_enable_bit_mask = {{ device.quad_enable_bit_mask }}, \ + .has_sector_protection = {{ device.has_sector_protection | lower() }}, \ + .supports_fast_read = {{ device.supports_fast_read | lower() }}, \ + .supports_qspi = {{ device["6b_quad_read"] | lower() }}, \ + .supports_qspi_writes = {{ device["32_qspi_write"] | lower() }}, \ + .write_status_register_split = {{ device.write_status_register_split | lower() }}, \ + .single_status_byte = {{ (device.quad_enable_status_byte == 1) | lower() }}, \ +} +{% endfor %} + +#endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_DEVICES_H diff --git a/supervisor/shared/external_flash/external_flash.c b/supervisor/shared/external_flash/external_flash.c index e2d767235ee73..722393ce656f5 100644 --- a/supervisor/shared/external_flash/external_flash.c +++ b/supervisor/shared/external_flash/external_flash.c @@ -27,6 +27,7 @@ #include #include +#include "genhdr/devices.h" #include "supervisor/flash.h" #include "supervisor/spi_flash_api.h" #include "supervisor/shared/external_flash/common_commands.h" @@ -45,21 +46,22 @@ // The currently cached sector in the cache, ram or flash based. static uint32_t current_sector; -const external_flash_device possible_devices[EXTERNAL_FLASH_DEVICE_COUNT] = {EXTERNAL_FLASH_DEVICES}; +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; } @@ -76,7 +78,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; } @@ -89,13 +91,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++) { @@ -110,14 +112,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; } } @@ -127,7 +129,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; } @@ -161,7 +163,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; } @@ -208,33 +210,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}; @@ -249,7 +251,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); } @@ -260,14 +262,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 @@ -311,7 +313,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) { @@ -324,7 +326,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; } @@ -340,8 +342,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++) { @@ -445,8 +447,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]); } @@ -463,7 +465,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. @@ -475,7 +477,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 } @@ -513,8 +515,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 { @@ -562,8 +564,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 cb1b86d1935ed..0613c9a57d51e 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 48266540c425c..dc16f3465b1d7 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 b72e37b268cfb..c0c089ee0f94f 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 67e64c970ec29..4f7d5f6d3aa43 100644 --- a/supervisor/shared/external_flash/spi_flash.c +++ b/supervisor/shared/external_flash/spi_flash.c @@ -38,13 +38,16 @@ 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)) {} - common_hal_digitalio_digitalinout_set_value(&cs_pin, false); +static bool flash_enable(void) { + if (common_hal_busio_spi_try_lock(&supervisor_flash_spi_bus)) { + common_hal_digitalio_digitalinout_set_value(&cs_pin, false); + return true; + } + return false; } // Disable the flash over SPI. @@ -54,7 +57,9 @@ static void flash_disable(void) { } static bool transfer(uint8_t* command, uint32_t command_length, uint8_t* data_in, uint8_t* data_out, uint32_t data_length) { - flash_enable(); + if (!flash_enable()) { + return false; + } bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, command, command_length); if (status) { if (data_in != NULL && data_out != NULL) { @@ -69,7 +74,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 +82,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,11 +103,13 @@ 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); - flash_enable(); + if (!flash_enable()) { + return false; + } common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8); bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, 4); if (status) { @@ -112,16 +119,18 @@ 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) { request[0] = CMD_FAST_READ_DATA; command_length = 5; } - // Write the SPI flash write address into the bytes following the command byte. + // Write the SPI flash read address into the bytes following the command byte. address_to_bytes(address, request + 1); - flash_enable(); + if (!flash_enable()) { + return false; + } common_hal_busio_spi_configure(&supervisor_flash_spi_bus, spi_flash_baudrate, 0, 0, 8); bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, request, command_length); if (status) { @@ -145,7 +154,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 09b30b6bad4e9..874f258217fa2 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 1e09fe14b33cd..33314adf1adb2 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 480c322b0112e..30482ea7b9bf2 --- 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 + #if INTERNAL_FLASH_FILESYSTEM == 0 + + 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 + #endif + + CIRCUITPY_DISPLAY_LIMIT * ( + // Maximum needs of one display: max(4 if RGBMATRIX, 1 if SHARPDISPLAY, 0) + #if CIRCUITPY_RGBMATRIX 4 - #elif CIRCUITPY_SHARPDISPLAY + #elif CIRCUITPY_SHARPDISPLAY 1 - #else + #else 0 + #endif + ) #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 bbc4807f97527..c68c4bf7e993d 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 c723fbab36580..581c177442019 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 006bb1b34c83c..d6e11c2aef48b 100644 --- a/supervisor/shared/rgb_led_status.c +++ b/supervisor/shared/rgb_led_status.c @@ -47,7 +47,6 @@ static uint8_t status_apa102_color[APA102_BUFFER_LENGTH] = {0, 0, 0, 0, 0xff, 0, #if CIRCUITPY_BITBANG_APA102 #include "shared-bindings/bitbangio/SPI.h" -#include "shared-module/bitbangio/types.h" static bitbangio_spi_obj_t status_apa102 = { .base = { .type = &bitbangio_spi_type, @@ -105,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 @@ -183,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 } @@ -204,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 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; + } + 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 #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; - - #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); + 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); #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 - - 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]); + 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]); #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; - - 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; + 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}; + + #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; - - #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); + 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 + + 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 } @@ -344,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; @@ -356,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(); @@ -411,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) { @@ -443,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 84c97796a44aa..753a1167cb623 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 b37b38e08874d..cd73e1b9f97c8 100644 --- a/supervisor/shared/safe_mode.c +++ b/supervisor/shared/safe_mode.c @@ -59,7 +59,8 @@ safe_mode_t wait_for_safe_mode_reset(void) { const mcu_reset_reason_t reset_reason = common_hal_mcu_processor_get_reset_reason(); if (reset_reason != RESET_REASON_POWER_ON && - reset_reason != RESET_REASON_RESET_PIN) { + reset_reason != RESET_REASON_RESET_PIN && + reset_reason != RESET_REASON_UNKNOWN) { return NO_SAFE_MODE; } port_set_saved_word(SAFE_MODE_DATA_GUARD | (MANUAL_SAFE_MODE << 8)); @@ -84,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; @@ -127,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: @@ -169,21 +170,21 @@ void print_safe_mode_message(safe_mode_t reason) { serial_write_compressed(translate("Crash into the HardFault_Handler.")); return; case MICROPY_NLR_JUMP_FAIL: - serial_write_compressed(translate("MicroPython NLR jump failed. Likely memory corruption.")); + serial_write_compressed(translate("NLR jump failed. Likely memory corruption.")); return; case MICROPY_FATAL_ERROR: - serial_write_compressed(translate("MicroPython fatal error.")); + serial_write_compressed(translate("Fatal error.")); break; case GC_ALLOC_OUTSIDE_VM: - serial_write_compressed(translate("Attempted heap allocation when MicroPython VM not running.")); + serial_write_compressed(translate("Attempted heap allocation when 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.")); + serial_write_compressed(translate("Nordic system firmware 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 34fc3c8ae1bf0..722e970333875 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 303f89e7521ab..bd2bf4ba22c99 100644 --- a/supervisor/shared/serial.c +++ b/supervisor/shared/serial.c @@ -28,6 +28,7 @@ #include "py/mpconfig.h" +#include "supervisor/shared/cpu.h" #include "supervisor/shared/display.h" #include "shared-bindings/terminalio/Terminal.h" #include "supervisor/serial.h" @@ -47,18 +48,22 @@ busio_uart_obj_t debug_uart; byte buf_array[64]; #endif +#if CIRCUITPY_USB_VENDOR +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) { @@ -66,56 +71,85 @@ void serial_init(void) { } bool serial_connected(void) { -#if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #if CIRCUITPY_USB_VENDOR + if (tud_vendor_connected()) { + return true; + } + #endif + + #if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) return true; -#else + #else return tud_cdc_connected(); -#endif + #endif } char serial_read(void) { -#if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #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 + + #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 defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #if CIRCUITPY_USB_VENDOR + if (tud_vendor_connected() && tud_vendor_available() > 0) { + return true; + } + #endif + + #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 (tud_vendor_connected()) { + tud_vendor_write(text, length); + } + #endif uint32_t count = 0; while (count < length && tud_cdc_connected()) { count += tud_cdc_write(text + count, length - count); + // If we're in an interrupt, then don't wait for more room. Queue up what we can. + if (cpu_interrupt_active()) { + break; + } 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 afea204010d7e..f3077b46c3d68 --- 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 1c75de5f78ba0..98cc5a16856bf --- 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 e51c48c7396c4..f40151988e98d 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 8bd3c5acdee8f..7afbd43e2159a 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,10 +83,10 @@ 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]; + uint8_t b = (&compressed->data)[this_byte] << (compress_max_length_bits % 8); uint16_t length = decompress_length(compressed); // Stop one early because the last byte is always NULL. @@ -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 QDEF(id, hash, len, 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 16296a4161392..2c440acc14abd 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 15d9fabafed04..0b23d56b9b9f2 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,19 +55,25 @@ #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_ENDOINT0_SIZE 64 +#define CFG_TUD_ENDPOINT0_SIZE 64 -//------------- CLASS -------------// +// ------------- CLASS -------------// + +// Could be 2 if secondary CDC channel requested. +#ifndef CFG_TUD_CDC #define CFG_TUD_CDC 1 -#define CFG_TUD_MSC 1 +#endif + +#define CFG_TUD_MSC CIRCUITPY_USB_MSC #define CFG_TUD_HID CIRCUITPY_USB_HID #define CFG_TUD_MIDI CIRCUITPY_USB_MIDI +#define CFG_TUD_VENDOR CIRCUITPY_USB_VENDOR #define CFG_TUD_CUSTOM_CLASS 0 /*------------------------------------------------------------------*/ @@ -78,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 07c6aee6c1a31..ea5faaf06bcf8 100644 --- a/supervisor/shared/usb/usb.c +++ b/supervisor/shared/usb/usb.c @@ -26,7 +26,6 @@ #include "py/objstr.h" #include "shared-bindings/microcontroller/Processor.h" -#include "shared-module/usb_midi/__init__.h" #include "supervisor/background_callback.h" #include "supervisor/port.h" #include "supervisor/serial.h" @@ -35,8 +34,25 @@ #include "lib/utils/interrupt_char.h" #include "lib/mp-readline/readline.h" +#if CIRCUITPY_USB_MIDI +#include "shared-module/usb_midi/__init__.h" +#endif + #include "tusb.h" +#if CIRCUITPY_USB_VENDOR +#include "genhdr/autogen_usb_descriptor.h" + +// The WebUSB support being conditionally added to this file is based on the +// tinyusb demo examples/device/webusb_serial. + +extern const tusb_desc_webusb_url_t desc_webusb_url; + +static bool web_serial_connected = false; +#endif + + + // Serial number as hex characters. This writes directly to the USB // descriptor. extern uint16_t usb_serial_number[1 + COMMON_HAL_MCU_PROCESSOR_UID_LENGTH * 2]; @@ -46,6 +62,7 @@ void load_serial_number(void) { uint8_t raw_id[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH]; common_hal_mcu_processor_get_uid(raw_id); + usb_serial_number[0] = 0x300 | sizeof(usb_serial_number); for (int i = 0; i < COMMON_HAL_MCU_PROCESSOR_UID_LENGTH; i++) { for (int j = 0; j < 2; j++) { uint8_t nibble = (raw_id[i] >> (j * 4)) & 0xf; @@ -59,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(); @@ -69,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) { @@ -94,27 +112,35 @@ 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) { + background_callback_add(&usb_callback, usb_background_do, NULL); +} + void usb_irq_handler(void) { tud_int_handler(0); - background_callback_add(&usb_callback, usb_background_do, NULL); + usb_background_schedule(); } -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // tinyusb callbacks -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // Invoked when device is mounted void tud_mount_cb(void) { + #if CIRCUITPY_USB_MSC usb_msc_mount(); + #endif } // Invoked when device is unmounted void tud_umount_cb(void) { + #if CIRCUITPY_USB_MSC usb_msc_umount(); + #endif } // Invoked when usb bus is suspended @@ -130,21 +156,73 @@ 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; +} + +// 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; + } + + 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); + + 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); + + // response with status OK + return tud_control_status(rhport, request); + + default: + // stall unknown request + return false; + } + + return true; +} +#endif // CIRCUITPY_USB_VENDOR + + #if MICROPY_KBD_EXCEPTION /** @@ -152,9 +230,8 @@ void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { * @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 080187ebc55a3..67df4f44bf857 100644 --- a/supervisor/shared/usb/usb_desc.c +++ b/supervisor/shared/usb/usb_desc.c @@ -31,28 +31,31 @@ // 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; } +#if CIRCUITPY_USB_HID // 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(void) { - return hid_report_descriptor; +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 7532b6aead524..409bf0ea6cd33 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/shared/workflow.h b/supervisor/shared/workflow.h index 22a9fa4684058..2596dd2c45af0 100644 --- a/supervisor/shared/workflow.h +++ b/supervisor/shared/workflow.h @@ -26,7 +26,5 @@ #pragma once -extern void supervisor_workflow_reset(void); - extern bool supervisor_workflow_connecting(void); extern bool supervisor_workflow_active(void); diff --git a/supervisor/spi_flash_api.h b/supervisor/spi_flash_api.h index f59346e25a858..1af83736dfe6d 100644 --- a/supervisor/spi_flash_api.h +++ b/supervisor/spi_flash_api.h @@ -29,21 +29,21 @@ #include #include -#include "supervisor/shared/external_flash/devices.h" +#include "shared/external_flash/device.h" #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 1c4a3e12dda83..2b518f41427aa 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 a70ac6b6d039a..b62cc05d7859f 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 34b433e536386..6ca14fcfde631 100644 --- a/supervisor/stub/serial.c +++ b/supervisor/stub/serial.c @@ -25,6 +25,7 @@ */ #include "supervisor/serial.h" +#include "supervisor/workflow.h" void serial_early_init(void) { @@ -46,6 +47,9 @@ bool serial_bytes_available(void) { return false; } -void serial_write(const char* text) { - (void) text; +void serial_write(const char *text) { + (void)text; +} + +void supervisor_workflow_reset(void) { } diff --git a/supervisor/stub/stack.c b/supervisor/stub/stack.c index 9a9ecd32f6f8e..2abc197878ceb 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/supervisor/supervisor.mk b/supervisor/supervisor.mk index a59e99e3def2b..eb81ea500717d 100644 --- a/supervisor/supervisor.mk +++ b/supervisor/supervisor.mk @@ -4,6 +4,7 @@ SRC_SUPERVISOR = \ supervisor/shared/autoreload.c \ supervisor/shared/background_callback.c \ supervisor/shared/board.c \ + supervisor/shared/cpu.c \ supervisor/shared/filesystem.c \ supervisor/shared/flash.c \ supervisor/shared/micropython.c \ @@ -14,23 +15,15 @@ SRC_SUPERVISOR = \ supervisor/shared/tick.c \ supervisor/shared/translate.c -ifndef $(NO_USB) - NO_USB = $(wildcard supervisor/usb.c) -endif +NO_USB ?= $(wildcard supervisor/usb.c) -ifndef INTERNAL_FLASH_FILESYSTEM -INTERNAL_FLASH_FILESYSTEM = 0 -endif +INTERNAL_FLASH_FILESYSTEM ?= 0 CFLAGS += -DINTERNAL_FLASH_FILESYSTEM=$(INTERNAL_FLASH_FILESYSTEM) -ifndef QSPI_FLASH_FILESYSTEM -QSPI_FLASH_FILESYSTEM = 0 -endif +QSPI_FLASH_FILESYSTEM ?= 0 CFLAGS += -DQSPI_FLASH_FILESYSTEM=$(QSPI_FLASH_FILESYSTEM) -ifndef SPI_FLASH_FILESYSTEM -SPI_FLASH_FILESYSTEM = 0 -endif +SPI_FLASH_FILESYSTEM ?= 0 CFLAGS += -DSPI_FLASH_FILESYSTEM=$(SPI_FLASH_FILESYSTEM) ifeq ($(CIRCUITPY_BLEIO),1) @@ -40,142 +33,187 @@ endif # Choose which flash filesystem impl to use. # (Right now INTERNAL_FLASH_FILESYSTEM and (Q)SPI_FLASH_FILESYSTEM are mutually exclusive. # But that might not be true in the future.) -ifdef EXTERNAL_FLASH_DEVICES - CFLAGS += -DEXTERNAL_FLASH_DEVICES=$(EXTERNAL_FLASH_DEVICES) \ - -DEXTERNAL_FLASH_DEVICE_COUNT=$(EXTERNAL_FLASH_DEVICE_COUNT) - - SRC_SUPERVISOR += supervisor/shared/external_flash/external_flash.c - ifeq ($(SPI_FLASH_FILESYSTEM),1) - SRC_SUPERVISOR += supervisor/shared/external_flash/spi_flash.c - else - endif - ifeq ($(QSPI_FLASH_FILESYSTEM),1) - SRC_SUPERVISOR += supervisor/qspi_flash.c supervisor/shared/external_flash/qspi_flash.c - endif +ifeq ($(INTERNAL_FLASH_FILESYSTEM),1) + ifeq ($(DISABLE_FILESYSTEM),1) + SRC_SUPERVISOR += supervisor/stub/internal_flash.c + else + SRC_SUPERVISOR += supervisor/internal_flash.c + endif else - ifeq ($(DISABLE_FILESYSTEM),1) - SRC_SUPERVISOR += supervisor/stub/internal_flash.c - else - SRC_SUPERVISOR += supervisor/internal_flash.c - endif -endif - -ifeq ($(USB),FALSE) - ifeq ($(wildcard supervisor/serial.c),) - SRC_SUPERVISOR += supervisor/stub/serial.c - else - SRC_SUPERVISOR += supervisor/serial.c - endif + CFLAGS += -DEXTERNAL_FLASH_DEVICES=$(EXTERNAL_FLASH_DEVICES) \ + + SRC_SUPERVISOR += supervisor/shared/external_flash/external_flash.c + ifeq ($(SPI_FLASH_FILESYSTEM),1) + SRC_SUPERVISOR += supervisor/shared/external_flash/spi_flash.c + endif + ifeq ($(QSPI_FLASH_FILESYSTEM),1) + SRC_SUPERVISOR += supervisor/qspi_flash.c supervisor/shared/external_flash/qspi_flash.c + endif + +$(HEADER_BUILD)/devices.h : ../../supervisor/shared/external_flash/devices.h.jinja ../../tools/gen_nvm_devices.py | $(HEADER_BUILD) + $(STEPECHO) "GEN $@" + $(Q)install -d $(BUILD)/genhdr + $(Q)$(PYTHON3) ../../tools/gen_nvm_devices.py $< $@ + +$(BUILD)/supervisor/shared/external_flash/external_flash.o: $(HEADER_BUILD)/devices.h + +endif + +ifeq ($(CIRCUITPY_USB),0) + ifeq ($(wildcard supervisor/serial.c),) + SRC_SUPERVISOR += supervisor/stub/serial.c + else + SRC_SUPERVISOR += supervisor/serial.c + endif else - SRC_SUPERVISOR += \ - lib/tinyusb/src/common/tusb_fifo.c \ - lib/tinyusb/src/device/usbd.c \ - lib/tinyusb/src/device/usbd_control.c \ - lib/tinyusb/src/class/msc/msc_device.c \ - lib/tinyusb/src/class/cdc/cdc_device.c \ - lib/tinyusb/src/tusb.c \ - supervisor/shared/serial.c \ - supervisor/shared/workflow.c \ - supervisor/usb.c \ - supervisor/shared/usb/usb_desc.c \ - supervisor/shared/usb/usb.c \ - supervisor/shared/usb/usb_msc_flash.c \ - $(BUILD)/autogen_usb_descriptor.c - - ifeq ($(CIRCUITPY_USB_HID), 1) - SRC_SUPERVISOR += \ - lib/tinyusb/src/class/hid/hid_device.c \ - shared-bindings/usb_hid/__init__.c \ - shared-bindings/usb_hid/Device.c \ - shared-module/usb_hid/__init__.c \ - shared-module/usb_hid/Device.c - endif - - ifeq ($(CIRCUITPY_USB_MIDI), 1) - SRC_SUPERVISOR += \ - lib/tinyusb/src/class/midi/midi_device.c \ - shared-bindings/usb_midi/__init__.c \ - shared-bindings/usb_midi/PortIn.c \ - shared-bindings/usb_midi/PortOut.c \ - shared-module/usb_midi/__init__.c \ - shared-module/usb_midi/PortIn.c \ - shared-module/usb_midi/PortOut.c - endif - - CFLAGS += -DUSB_AVAILABLE + SRC_SUPERVISOR += \ + lib/tinyusb/src/class/cdc/cdc_device.c \ + lib/tinyusb/src/common/tusb_fifo.c \ + lib/tinyusb/src/device/usbd.c \ + lib/tinyusb/src/device/usbd_control.c \ + lib/tinyusb/src/tusb.c \ + supervisor/shared/serial.c \ + supervisor/shared/workflow.c \ + supervisor/usb.c \ + supervisor/shared/usb/usb_desc.c \ + supervisor/shared/usb/usb.c \ + $(BUILD)/autogen_usb_descriptor.c \ + + ifeq ($(CIRCUITPY_USB_CDC), 1) + SRC_SUPERVISOR += \ + shared-bindings/usb_cdc/__init__.c \ + shared-bindings/usb_cdc/Serial.c \ + shared-module/usb_cdc/__init__.c \ + shared-module/usb_cdc/Serial.c \ + + endif + + ifeq ($(CIRCUITPY_USB_HID), 1) + SRC_SUPERVISOR += \ + lib/tinyusb/src/class/hid/hid_device.c \ + shared-bindings/usb_hid/__init__.c \ + shared-bindings/usb_hid/Device.c \ + shared-module/usb_hid/__init__.c \ + shared-module/usb_hid/Device.c \ + + endif + + ifeq ($(CIRCUITPY_USB_MIDI), 1) + SRC_SUPERVISOR += \ + lib/tinyusb/src/class/midi/midi_device.c \ + shared-bindings/usb_midi/__init__.c \ + shared-bindings/usb_midi/PortIn.c \ + shared-bindings/usb_midi/PortOut.c \ + shared-module/usb_midi/__init__.c \ + shared-module/usb_midi/PortIn.c \ + shared-module/usb_midi/PortOut.c \ + + endif + + ifeq ($(CIRCUITPY_USB_MSC), 1) + SRC_SUPERVISOR += \ + lib/tinyusb/src/class/msc/msc_device.c \ + supervisor/shared/usb/usb_msc_flash.c \ + + endif + + ifeq ($(CIRCUITPY_USB_VENDOR), 1) + SRC_SUPERVISOR += \ + lib/tinyusb/src/class/vendor/vendor_device.c \ + + endif endif SUPERVISOR_O = $(addprefix $(BUILD)/, $(SRC_SUPERVISOR:.c=.o)) ifeq ($(CIRCUITPY_DISPLAYIO), 1) - SRC_SUPERVISOR += \ - supervisor/shared/display.c + SRC_SUPERVISOR += \ + supervisor/shared/display.c - ifeq ($(CIRCUITPY_TERMINALIO), 1) - SUPERVISOR_O += $(BUILD)/autogen_display_resources.o - endif + ifeq ($(CIRCUITPY_TERMINALIO), 1) + SUPERVISOR_O += $(BUILD)/autogen_display_resources.o + endif endif -ifndef USB_INTERFACE_NAME -USB_INTERFACE_NAME = "CircuitPython" + +USB_INTERFACE_NAME ?= "CircuitPython" + +ifneq ($(USB_VID),) +CFLAGS += -DUSB_VID=$(USB_VID) +CFLAGS += -DSUB_PID=$(USB_PID) +CFLAGS += -DUSB_MANUFACTURER=$(USB_MANUFACTURER) +CFLAGS += -DUSB_PRODUCT=$(USB_PRODUCT) endif -USB_DEVICES_COMPUTED := CDC,MSC -ifeq ($(CIRCUITPY_USB_MIDI),1) -USB_DEVICES_COMPUTED := $(USB_DEVICES_COMPUTED),AUDIO +# In the following URL, don't include the https:// prefix. +# It gets added automatically. +USB_WEBUSB_URL ?= "circuitpython.org" + +ifeq ($(CIRCUITPY_REPL_USB),1) +USB_DEVICES += CDC endif + ifeq ($(CIRCUITPY_USB_HID),1) -USB_DEVICES_COMPUTED := $(USB_DEVICES_COMPUTED),HID +USB_DEVICES += HID endif -USB_DEVICES ?= "$(USB_DEVICES_COMPUTED)" - -ifndef USB_HID_DEVICES -USB_HID_DEVICES = "KEYBOARD,MOUSE,CONSUMER,GAMEPAD" +ifeq ($(CIRCUITPY_USB_MIDI),1) +USB_DEVICES += AUDIO endif - -ifndef USB_HIGHSPEED -USB_HIGHSPEED = 0 +ifeq ($(CIRCUITPY_USB_MSC),1) +USB_DEVICES += MSC endif - -ifndef USB_CDC_EP_NUM_NOTIFICATION -USB_CDC_EP_NUM_NOTIFICATION = 0 +ifeq ($(CIRCUITPY_USB_CDC),1) +# Inform TinyUSB there are two CDC devices. +CFLAGS += -DCFG_TUD_CDC=2 +USB_DEVICES += CDC2 endif - -ifndef USB_CDC_EP_NUM_DATA_OUT -USB_CDC_EP_NUM_DATA_OUT = 0 +ifeq ($(CIRCUITPY_USB_VENDOR),1) +USB_DEVICES += VENDOR endif -ifndef USB_CDC_EP_NUM_DATA_IN -USB_CDC_EP_NUM_DATA_IN = 0 +USB_HID_DEVICES = +ifeq ($(CIRCUITPY_USB_HID_CONSUMER),1) +USB_HID_DEVICES += CONSUMER endif - -ifndef USB_MSC_EP_NUM_OUT -USB_MSC_EP_NUM_OUT = 0 +ifeq ($(CIRCUITPY_USB_HID_DIGITIZER),1) +USB_HID_DEVICES += DIGITIZER endif - -ifndef USB_MSC_EP_NUM_IN -USB_MSC_EP_NUM_IN = 0 +ifeq ($(CIRCUITPY_USB_HID_GAMEPAD),1) +USB_HID_DEVICES += GAMEPAD endif - -ifndef USB_HID_EP_NUM_OUT -USB_HID_EP_NUM_OUT = 0 +ifeq ($(CIRCUITPY_USB_HID_KEYBOARD),1) +USB_HID_DEVICES += KEYBOARD endif - -ifndef USB_HID_EP_NUM_IN -USB_HID_EP_NUM_IN = 0 +ifeq ($(CIRCUITPY_USB_HID_MOUSE),1) +USB_HID_DEVICES += MOUSE endif - -ifndef USB_MIDI_EP_NUM_OUT -USB_MIDI_EP_NUM_OUT = 0 +ifeq ($(CIRCUITPY_USB_HID_SYS_CONTROL),1) +USB_HID_DEVICES += SYS_CONTROL endif - -ifndef USB_MIDI_EP_NUM_IN -USB_MIDI_EP_NUM_IN = 0 +ifeq ($(CIRCUITPY_USB_HID_XAC_COMPATIBLE_GAMEPAD),1) +USB_HID_DEVICES += XAC_COMPATIBLE_GAMEPAD endif -ifndef USB_NUM_EP -USB_NUM_EP = 0 +# RAW is not compatible with other HID devices. +ifeq ($(CIRCUITPY_USB_HID_RAW),1) + ifneq ($(CIRCUITPY_USB_HID_DEVICES,) + $(error HID RAW must not be combined with other HID devices) +endif +USB_HID_DEVICES += MOUSE endif +USB_HIGHSPEED ?= 0 + +USB_CDC_EP_NUM_NOTIFICATION ?= 0 +USB_CDC_EP_NUM_DATA_OUT ?= 0 +USB_CDC_EP_NUM_DATA_IN ?= 0 +USB_MSC_EP_NUM_OUT ?= 0 +USB_MSC_EP_NUM_IN ?= 0 +USB_HID_EP_NUM_OUT ?= 0 +USB_HID_EP_NUM_IN ?= 0 +USB_MIDI_EP_NUM_OUT ?= 0 +USB_MIDI_EP_NUM_IN ?= 0 +USB_NUM_EP ?= 0 + USB_DESCRIPTOR_ARGS = \ --manufacturer $(USB_MANUFACTURER)\ --product $(USB_PRODUCT)\ @@ -183,8 +221,8 @@ USB_DESCRIPTOR_ARGS = \ --pid $(USB_PID)\ --serial_number_length $(USB_SERIAL_NUMBER_LENGTH)\ --interface_name $(USB_INTERFACE_NAME)\ - --devices $(USB_DEVICES)\ - --hid_devices $(USB_HID_DEVICES)\ + --devices "$(USB_DEVICES)"\ + --hid_devices "$(USB_HID_DEVICES)"\ --max_ep $(USB_NUM_EP) \ --cdc_ep_num_notification $(USB_CDC_EP_NUM_NOTIFICATION)\ --cdc_ep_num_data_out $(USB_CDC_EP_NUM_DATA_OUT)\ @@ -198,6 +236,12 @@ USB_DESCRIPTOR_ARGS = \ --output_c_file $(BUILD)/autogen_usb_descriptor.c\ --output_h_file $(BUILD)/genhdr/autogen_usb_descriptor.h +ifeq ($(CIRCUITPY_USB_VENDOR), 1) +USB_DESCRIPTOR_ARGS += \ + --vendor_ep_num_out 0 --vendor_ep_num_in 0 \ + --webusb_url $(USB_WEBUSB_URL) +endif + ifeq ($(USB_RENUMBER_ENDPOINTS), 0) USB_DESCRIPTOR_ARGS += --no-renumber_endpoints endif diff --git a/supervisor/usb.h b/supervisor/usb.h index ccb35470cd0d5..f8fd713715f1c 100644 --- a/supervisor/usb.h +++ b/supervisor/usb.h @@ -35,6 +35,9 @@ // it may be necessary to call it directly. void usb_background(void); +// Schedule usb background +void usb_background_schedule(void); + // Ports must call this from their particular USB IRQ handler void usb_irq_handler(void); @@ -51,8 +54,10 @@ void usb_init(void); void usb_disconnect(void); // Propagate plug/unplug events to the MSC logic. +#if CIRCUITPY_USB_MSC void usb_msc_mount(void); void usb_msc_umount(void); bool usb_msc_ejected(void); +#endif #endif // MICROPY_INCLUDED_SUPERVISOR_USB_H diff --git a/supervisor/workflow.h b/supervisor/workflow.h index 4008b83a11fec..27d063503a9b2 100755 --- a/supervisor/workflow.h +++ b/supervisor/workflow.h @@ -26,5 +26,7 @@ #pragma once +void supervisor_workflow_reset(void); + // True when the user could be actively iterating on their code. bool workflow_active(void); diff --git a/tests/basics/async_with_break.py b/tests/basics/async_with_break.py new file mode 100644 index 0000000000000..39bcbccb025e6 --- /dev/null +++ b/tests/basics/async_with_break.py @@ -0,0 +1,59 @@ +# test async with, escaped by a break + +class AContext: + async def __aenter__(self): + print('enter') + return 1 + async def __aexit__(self, exc_type, exc, tb): + print('exit', exc_type, exc) + +async def f1(): + while 1: + async with AContext(): + print('body') + break + print('no 1') + print('no 2') + +o = f1() +try: + print(o.send(None)) +except StopIteration: + print('finished') + +async def f2(): + while 1: + try: + async with AContext(): + print('body') + break + print('no 1') + finally: + print('finally') + print('no 2') + +o = f2() +try: + print(o.send(None)) +except StopIteration: + print('finished') + +async def f3(): + while 1: + try: + try: + async with AContext(): + print('body') + break + print('no 1') + finally: + print('finally inner') + finally: + print('finally outer') + print('no 2') + +o = f3() +try: + print(o.send(None)) +except StopIteration: + print('finished') diff --git a/tests/basics/async_with_break.py.exp b/tests/basics/async_with_break.py.exp new file mode 100644 index 0000000000000..d077a88fad0e4 --- /dev/null +++ b/tests/basics/async_with_break.py.exp @@ -0,0 +1,15 @@ +enter +body +exit None None +finished +enter +body +exit None None +finally +finished +enter +body +exit None None +finally inner +finally outer +finished diff --git a/tests/basics/async_with_return.py b/tests/basics/async_with_return.py new file mode 100644 index 0000000000000..9af88b839f88c --- /dev/null +++ b/tests/basics/async_with_return.py @@ -0,0 +1,50 @@ +# test async with, escaped by a return + +class AContext: + async def __aenter__(self): + print('enter') + return 1 + async def __aexit__(self, exc_type, exc, tb): + print('exit', exc_type, exc) + +async def f1(): + async with AContext(): + print('body') + return + +o = f1() +try: + o.send(None) +except StopIteration: + print('finished') + +async def f2(): + try: + async with AContext(): + print('body') + return + finally: + print('finally') + +o = f2() +try: + o.send(None) +except StopIteration: + print('finished') + +async def f3(): + try: + try: + async with AContext(): + print('body') + return + finally: + print('finally inner') + finally: + print('finally outer') + +o = f3() +try: + o.send(None) +except StopIteration: + print('finished') diff --git a/tests/basics/async_with_return.py.exp b/tests/basics/async_with_return.py.exp new file mode 100644 index 0000000000000..d077a88fad0e4 --- /dev/null +++ b/tests/basics/async_with_return.py.exp @@ -0,0 +1,15 @@ +enter +body +exit None None +finished +enter +body +exit None None +finally +finished +enter +body +exit None None +finally inner +finally outer +finished diff --git a/tests/basics/bytearray_construct.py b/tests/basics/bytearray_construct.py index 9c8f3adaaa7f6..75fdc411782b8 100644 --- a/tests/basics/bytearray_construct.py +++ b/tests/basics/bytearray_construct.py @@ -1,6 +1,7 @@ # test construction of bytearray from different objects -# bytes, tuple, list print(bytearray(b'123')) +print(bytearray('1234', 'utf-8')) +print(bytearray('12345', 'utf-8', 'strict')) print(bytearray((1, 2))) print(bytearray([1, 2])) diff --git a/tests/basics/bytes_count.py b/tests/basics/bytes_count.py index 95bcfe310e628..5fa0730f5cff0 100644 --- a/tests/basics/bytes_count.py +++ b/tests/basics/bytes_count.py @@ -1,3 +1,9 @@ +try: + bytes.count +except AttributeError: + print("SKIP") + raise SystemExit + print(b"".count(b"")) print(b"".count(b"a")) print(b"a".count(b"")) diff --git a/tests/basics/class_getattr.py b/tests/basics/class_getattr.py index 1f875ce5385f1..eadf2b209f00e 100644 --- a/tests/basics/class_getattr.py +++ b/tests/basics/class_getattr.py @@ -1,4 +1,4 @@ -# test that __getattr__, __getattrribute__ and instance members don't override builtins +# test that __getattr__ and instance members don't override builtins class C: def __init__(self): self.__add__ = lambda: print('member __add__') @@ -7,10 +7,8 @@ def __add__(self, x): def __getattr__(self, attr): print('__getattr__', attr) return None - def __getattrribute__(self, attr): - print('__getattrribute__', attr) - return None c = C() -c.__add__ -c + 1 # should call __add__ +c.add # should call __getattr__ +c.__add__() # should load __add__ instance directly +c + 1 # should call __add__ method directly diff --git a/tests/basics/class_staticclassmethod.py b/tests/basics/class_staticclassmethod.py index 1cb59d5c7b65e..edde419271435 100644 --- a/tests/basics/class_staticclassmethod.py +++ b/tests/basics/class_staticclassmethod.py @@ -17,9 +17,24 @@ def __sub__(rhs): def __add__(self, rhs): print('add', rhs) + # subscript special methods wrapped in staticmethod + @staticmethod + def __getitem__(item): + print('static get', item) + return 'item' + @staticmethod + def __setitem__(item, value): + print('static set', item, value) + @staticmethod + def __delitem__(item): + print('static del', item) + c = C() c.f(0) c.g(0) c - 1 c + 2 +print(c[1]) +c[1] = 2 +del c[3] diff --git a/tests/basics/core_class_superproperty.py b/tests/basics/core_class_superproperty.py index 69db10046a273..3095ab51da105 100644 --- a/tests/basics/core_class_superproperty.py +++ b/tests/basics/core_class_superproperty.py @@ -1,15 +1,19 @@ """ test that calling super() getter property in subclass will return the value """ + + class A: @property def p(self): - return {"a":10} + return {"a": 10} + class AA(A): @property def p(self): return super().p + a = AA() print(a.p) diff --git a/tests/basics/fun_name.py b/tests/basics/fun_name.py index a724f41118084..53ca935616ce3 100644 --- a/tests/basics/fun_name.py +++ b/tests/basics/fun_name.py @@ -15,3 +15,10 @@ def Fun(self): except AttributeError: print('SKIP') raise SystemExit + +# __name__ of a bound native method is not implemented in uPy +# the test here is to make sure it doesn't crash +try: + str((1).to_bytes.__name__) +except AttributeError: + pass diff --git a/tests/basics/gen_yield_from.py b/tests/basics/gen_yield_from.py index 4e68aec63b9f2..037644e1ecbb8 100644 --- a/tests/basics/gen_yield_from.py +++ b/tests/basics/gen_yield_from.py @@ -13,34 +13,6 @@ def gen2(): print(list(g)) -# Like above, but terminate subgen using StopIteration -def gen3(): - yield 1 - yield 2 - raise StopIteration - -def gen4(): - print("here1") - print((yield from gen3())) - print("here2") - -g = gen4() -print(list(g)) - -# Like above, but terminate subgen using StopIteration with value -def gen5(): - yield 1 - yield 2 - raise StopIteration(123) - -def gen6(): - print("here1") - print((yield from gen5())) - print("here2") - -g = gen6() -print(list(g)) - # StopIteration from within a Python function, within a native iterator (map), within a yield from def gen7(x): if x < 3: diff --git a/tests/basics/gen_yield_from.py.exp b/tests/basics/gen_yield_from.py.exp deleted file mode 100644 index 507f2b9cafaea..0000000000000 --- a/tests/basics/gen_yield_from.py.exp +++ /dev/null @@ -1,14 +0,0 @@ -here1 -3 -here2 -[1, 2] -here1 -None -here2 -[1, 2] -here1 -123 -here2 -[1, 2] -444 -[0, 1, 2] diff --git a/tests/basics/gen_yield_from_close.py b/tests/basics/gen_yield_from_close.py index 8339861056f44..e3e0116ff7a6d 100644 --- a/tests/basics/gen_yield_from_close.py +++ b/tests/basics/gen_yield_from_close.py @@ -55,14 +55,14 @@ def gen4(): # Yet another variation - leaf generator gets GeneratorExit, -# but raises StopIteration instead. This still should close chain properly. +# and reraises a new GeneratorExit. This still should close chain properly. def gen5(): yield 1 try: yield 2 except GeneratorExit: - print("leaf caught GeneratorExit and raised StopIteration instead") - raise StopIteration(123) + print("leaf caught GeneratorExit and reraised GeneratorExit") + raise GeneratorExit(123) yield 3 yield 4 diff --git a/tests/basics/gen_yield_from_close.py.exp b/tests/basics/gen_yield_from_close.py.exp deleted file mode 100644 index a44d1353dfbeb..0000000000000 --- a/tests/basics/gen_yield_from_close.py.exp +++ /dev/null @@ -1,20 +0,0 @@ --1 -1 -StopIteration --1 -1 -2 -leaf caught GeneratorExit and swallowed it -delegating caught GeneratorExit -StopIteration --1 -1 -2 -leaf caught GeneratorExit and raised StopIteration instead -delegating caught GeneratorExit -StopIteration -123 -RuntimeError -0 -1 -close diff --git a/tests/basics/gen_yield_from_throw.py b/tests/basics/gen_yield_from_throw.py index d6754d5cd1ffd..703158f4d42ab 100644 --- a/tests/basics/gen_yield_from_throw.py +++ b/tests/basics/gen_yield_from_throw.py @@ -16,15 +16,3 @@ def gen2(): print(next(g)) except TypeError: print("got TypeError from downstream!") - -# case where generator doesn't intercept the thrown/injected exception -def gen3(): - yield 123 - yield 456 - -g3 = gen3() -print(next(g3)) -try: - g3.throw(StopIteration) -except StopIteration: - print('got StopIteration from downstream!') diff --git a/tests/basics/gen_yield_from_throw.py.exp b/tests/basics/gen_yield_from_throw.py.exp deleted file mode 100644 index 6ce97ad86e21f..0000000000000 --- a/tests/basics/gen_yield_from_throw.py.exp +++ /dev/null @@ -1,6 +0,0 @@ -1 -got ValueError from upstream! -str1 -got TypeError from downstream! -123 -got StopIteration from downstream! diff --git a/tests/basics/gen_yield_from_throw2.py b/tests/basics/gen_yield_from_throw2.py index 5c0fc7dbc96ff..6b59a7835a3b0 100644 --- a/tests/basics/gen_yield_from_throw2.py +++ b/tests/basics/gen_yield_from_throw2.py @@ -1,18 +1,24 @@ -# generator ignores a thrown GeneratorExit (this is allowed) +# outer generator ignores a thrown GeneratorExit (this is allowed) def gen(): try: yield 123 except GeneratorExit: print('GeneratorExit') - yield 456 + +def gen2(): + try: + yield from gen() + except GeneratorExit: + print('GeneratorExit outer') + yield 789 # thrown a class -g = gen() +g = gen2() print(next(g)) print(g.throw(GeneratorExit)) # thrown an instance -g = gen() +g = gen2() print(next(g)) print(g.throw(GeneratorExit())) diff --git a/tests/basics/generator_close.py b/tests/basics/generator_close.py index aa563f2a8aaf1..1ccc78dbe446b 100644 --- a/tests/basics/generator_close.py +++ b/tests/basics/generator_close.py @@ -31,13 +31,14 @@ def gen1(): print("StopIteration") -# Throwing StopIteration in response to close() is ok +# Throwing GeneratorExit in response to close() is ok def gen2(): try: yield 1 yield 2 except: - raise StopIteration + print('raising GeneratorExit') + raise GeneratorExit g = gen2() next(g) diff --git a/tests/basics/generator_close.py.exp b/tests/basics/generator_close.py.exp deleted file mode 100644 index fcd5839357d4e..0000000000000 --- a/tests/basics/generator_close.py.exp +++ /dev/null @@ -1,10 +0,0 @@ -None -StopIteration -1 -None -StopIteration -[1, 2] -None -StopIteration -None -ValueError diff --git a/tests/basics/generator_name.py b/tests/basics/generator_name.py new file mode 100644 index 0000000000000..77259a8218a3d --- /dev/null +++ b/tests/basics/generator_name.py @@ -0,0 +1,16 @@ +# test __name__ on generator functions + +def Fun(): + yield + +class A: + def Fun(self): + yield + +try: + print(Fun.__name__) + print(A.Fun.__name__) + print(A().Fun.__name__) +except AttributeError: + print('SKIP') + raise SystemExit diff --git a/tests/basics/generator_pep479.py b/tests/basics/generator_pep479.py new file mode 100644 index 0000000000000..e422c349e7522 --- /dev/null +++ b/tests/basics/generator_pep479.py @@ -0,0 +1,29 @@ +# tests for correct PEP479 behaviour (introduced in Python 3.5) + +# basic case: StopIteration is converted into a RuntimeError +def gen(): + yield 1 + raise StopIteration +g = gen() +print(next(g)) +try: + next(g) +except RuntimeError: + print('RuntimeError') + +# trying to continue a failed generator now raises StopIteration +try: + next(g) +except StopIteration: + print('StopIteration') + +# throwing a StopIteration which is uncaught will be converted into a RuntimeError +def gen(): + yield 1 + yield 2 +g = gen() +print(next(g)) +try: + g.throw(StopIteration) +except RuntimeError: + print('RuntimeError') diff --git a/tests/basics/generator_pep479.py.exp b/tests/basics/generator_pep479.py.exp new file mode 100644 index 0000000000000..c64fe49561a98 --- /dev/null +++ b/tests/basics/generator_pep479.py.exp @@ -0,0 +1,5 @@ +1 +RuntimeError +StopIteration +1 +RuntimeError diff --git a/tests/basics/generator_return.py b/tests/basics/generator_return.py index 5814ce8379cbb..2b3464a02aec5 100644 --- a/tests/basics/generator_return.py +++ b/tests/basics/generator_return.py @@ -8,3 +8,9 @@ def gen(): print(next(g)) except StopIteration as e: print(type(e), e.args) + +# trying next again should raise StopIteration with no arguments +try: + print(next(g)) +except StopIteration as e: + print(type(e), e.args) diff --git a/tests/basics/generator_throw.py b/tests/basics/generator_throw.py new file mode 100644 index 0000000000000..1a390f399daf6 --- /dev/null +++ b/tests/basics/generator_throw.py @@ -0,0 +1,43 @@ +# case where generator doesn't intercept the thrown/injected exception +def gen(): + yield 123 + yield 456 + +g = gen() +print(next(g)) +try: + g.throw(KeyError) +except KeyError: + print('got KeyError from downstream!') + +# case where a thrown exception is caught and stops the generator +def gen(): + try: + yield 1 + yield 2 + except: + pass +g = gen() +print(next(g)) +try: + g.throw(ValueError) +except StopIteration: + print('got StopIteration') + +# generator ignores a thrown GeneratorExit (this is allowed) +def gen(): + try: + yield 123 + except GeneratorExit: + print('GeneratorExit') + yield 456 + +# thrown a class +g = gen() +print(next(g)) +print(g.throw(GeneratorExit)) + +# thrown an instance +g = gen() +print(next(g)) +print(g.throw(GeneratorExit())) diff --git a/tests/basics/getattr.py b/tests/basics/getattr.py index a021e38fb0aef..2257da3bf96eb 100644 --- a/tests/basics/getattr.py +++ b/tests/basics/getattr.py @@ -9,3 +9,20 @@ def __getattr__(self, attr): a = A({'a':1, 'b':2}) print(a.a, a.b) + +# test that any exception raised in __getattr__ propagates out +class A: + def __getattr__(self, attr): + if attr == "value": + raise ValueError(123) + else: + raise AttributeError(456) +a = A() +try: + a.value +except ValueError as er: + print(er) +try: + a.attr +except AttributeError as er: + print(er) diff --git a/tests/io/buffered_writer.py b/tests/basics/io_buffered_writer.py similarity index 96% rename from tests/io/buffered_writer.py rename to tests/basics/io_buffered_writer.py index c2cedb9912339..64e5fa1ee75dc 100644 --- a/tests/io/buffered_writer.py +++ b/tests/basics/io_buffered_writer.py @@ -4,7 +4,7 @@ io.BytesIO io.BufferedWriter except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit bts = io.BytesIO() diff --git a/tests/io/buffered_writer.py.exp b/tests/basics/io_buffered_writer.py.exp similarity index 100% rename from tests/io/buffered_writer.py.exp rename to tests/basics/io_buffered_writer.py.exp diff --git a/tests/io/bytesio_cow.py b/tests/basics/io_bytesio_cow.py similarity index 100% rename from tests/io/bytesio_cow.py rename to tests/basics/io_bytesio_cow.py diff --git a/tests/io/bytesio_ext.py b/tests/basics/io_bytesio_ext.py similarity index 100% rename from tests/io/bytesio_ext.py rename to tests/basics/io_bytesio_ext.py diff --git a/tests/io/bytesio_ext2.py b/tests/basics/io_bytesio_ext2.py similarity index 100% rename from tests/io/bytesio_ext2.py rename to tests/basics/io_bytesio_ext2.py diff --git a/tests/io/bytesio_ext2.py.exp b/tests/basics/io_bytesio_ext2.py.exp similarity index 100% rename from tests/io/bytesio_ext2.py.exp rename to tests/basics/io_bytesio_ext2.py.exp diff --git a/tests/io/iobase.py b/tests/basics/io_iobase.py similarity index 77% rename from tests/io/iobase.py rename to tests/basics/io_iobase.py index 6f554b00f082d..667e629858e9c 100644 --- a/tests/io/iobase.py +++ b/tests/basics/io_iobase.py @@ -6,14 +6,15 @@ 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/stringio1.py b/tests/basics/io_stringio1.py similarity index 89% rename from tests/io/stringio1.py rename to tests/basics/io_stringio1.py index 9f7c1e44ef60c..6d84917547e70 100644 --- a/tests/io/stringio1.py +++ b/tests/basics/io_stringio1.py @@ -4,7 +4,7 @@ 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 @@ 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/stringio_with.py b/tests/basics/io_stringio_with.py similarity index 100% rename from tests/io/stringio_with.py rename to tests/basics/io_stringio_with.py diff --git a/tests/io/write_ext.py b/tests/basics/io_write_ext.py similarity index 96% rename from tests/io/write_ext.py rename to tests/basics/io_write_ext.py index 5a6eaa35cf039..18cd75ddb6483 100644 --- a/tests/io/write_ext.py +++ b/tests/basics/io_write_ext.py @@ -5,7 +5,7 @@ try: uio.BytesIO except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit buf = uio.BytesIO() diff --git a/tests/io/write_ext.py.exp b/tests/basics/io_write_ext.py.exp similarity index 100% rename from tests/io/write_ext.py.exp rename to tests/basics/io_write_ext.py.exp diff --git a/tests/basics/namedtuple_asdict.py b/tests/basics/namedtuple_asdict.py index c5681376fd4cb..34c4e6f7131b6 100644 --- a/tests/basics/namedtuple_asdict.py +++ b/tests/basics/namedtuple_asdict.py @@ -1,8 +1,8 @@ try: try: - from collections import namedtuple - except ImportError: from ucollections import namedtuple + except ImportError: + from collections import namedtuple except ImportError: print("SKIP") raise SystemExit diff --git a/tests/basics/op_precedence.py b/tests/basics/op_precedence.py index 519a2a1137dfa..7d8302ba4dec2 100644 --- a/tests/basics/op_precedence.py +++ b/tests/basics/op_precedence.py @@ -37,7 +37,7 @@ # BAD: (-2)**2 = 4 print(-2**2) # OK: 2**(-1) = 0.5 -print(2**-1) +print(2**-0) # (expr...) print((2 + 2) * 2) diff --git a/tests/basics/scope_implicit.py b/tests/basics/scope_implicit.py new file mode 100644 index 0000000000000..aecda7715633c --- /dev/null +++ b/tests/basics/scope_implicit.py @@ -0,0 +1,31 @@ +# test implicit scoping rules + +# implicit nonlocal, with variable defined after closure +def f(): + def g(): + return x # implicit nonlocal + x = 3 # variable defined after function that closes over it + return g +print(f()()) + +# implicit nonlocal at inner level, with variable defined after closure +def f(): + def g(): + def h(): + return x # implicit nonlocal + return h + x = 4 # variable defined after function that closes over it + return g +print(f()()()) + +# local variable which should not be implicitly made nonlocal +def f(): + x = 0 + def g(): + x # local because next statement assigns to it + x = 1 + g() +try: + f() +except NameError: + print('NameError') diff --git a/tests/basics/special_methods.py b/tests/basics/special_methods.py index 9f57247c12f1f..b56bc1c9c479d 100644 --- a/tests/basics/special_methods.py +++ b/tests/basics/special_methods.py @@ -93,6 +93,9 @@ def __isub__(self, other): print("__isub__ called") return self + def __int__(self): + return 42 + cud1 = Cud() cud2 = Cud() @@ -104,5 +107,16 @@ def __isub__(self, other): cud1 > cud2 cud1 + cud2 cud1 - cud2 +print(int(cud1)) + +class BadInt: + def __int__(self): + print("__int__ called") + return None + +try: + int(BadInt()) +except TypeError: + print("TypeError") # more in special_methods2.py diff --git a/tests/basics/special_methods2.py b/tests/basics/special_methods2.py index c21618e93db91..c72c8cf00f571 100644 --- a/tests/basics/special_methods2.py +++ b/tests/basics/special_methods2.py @@ -134,6 +134,6 @@ def __dir__(self): # ne is not supported, !(eq) is called instead #cud1 != cud2 # -# in the followin test, cpython still calls __eq__ +# in the following test, cpython still calls __eq__ # cud3=cud1 # cud3==cud1 diff --git a/tests/basics/string_count.py b/tests/basics/string_count.py index 462ccb8299ec5..8fb5c98f82739 100644 --- a/tests/basics/string_count.py +++ b/tests/basics/string_count.py @@ -1,3 +1,9 @@ +try: + str.count +except AttributeError: + print("SKIP") + raise SystemExit + print("".count("")) print("".count("a")) print("a".count("")) diff --git a/tests/basics/struct1.py b/tests/basics/struct1.py index 107006cc3fa08..ec29ea90801f8 100644 --- a/tests/basics/struct1.py +++ b/tests/basics/struct1.py @@ -121,3 +121,5 @@ # check padding bytes print(struct.pack("xb", 3)) +# Make sure pack doesn't reuse a larger value and error +print(struct.pack("xH", 0x100)) diff --git a/tests/basics/subclass_native_call.py b/tests/basics/subclass_native_call.py deleted file mode 100644 index c645575225989..0000000000000 --- a/tests/basics/subclass_native_call.py +++ /dev/null @@ -1,30 +0,0 @@ -# test calling a subclass of a native class that supports calling - -# For this test we need a native class that can be subclassed (has make_new) -# and is callable (has call). The only one available is machine.Signal, which -# in turns needs PinBase. -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.Signal -except AttributeError: - print("SKIP") - raise SystemExit - -class Pin(machine.PinBase): - #def __init__(self): - # self.v = 0 - - def value(self, v=None): - return 42 - -class MySignal(machine.Signal): - pass - -s = MySignal(Pin()) - -# apply call to the subclass, which should call the native base -print(s()) diff --git a/tests/basics/subclass_native_call.py.exp b/tests/basics/subclass_native_call.py.exp deleted file mode 100644 index d81cc0710eb6c..0000000000000 --- a/tests/basics/subclass_native_call.py.exp +++ /dev/null @@ -1 +0,0 @@ -42 diff --git a/tests/basics/try_finally1.py b/tests/basics/try_finally1.py index 2416f6d18842c..67ebe0b590787 100644 --- a/tests/basics/try_finally1.py +++ b/tests/basics/try_finally1.py @@ -69,3 +69,28 @@ def func2(): except: print("catch-all except") print() + +# case where a try-except within a finally cancels the exception +print("exc-finally-subexcept") +try: + print("try1") +finally: + try: + print("try2") + foo + except: + print("except2") + print("finally1") +print() + +# case where exception is raised after a finally has finished (tests that the finally doesn't run again) +def func(): + try: + print("try") + finally: + print("finally") + foo +try: + func() +except: + print("except") diff --git a/tests/basics/try_finally_return3.py b/tests/basics/try_finally_return3.py new file mode 100644 index 0000000000000..a2a06ee975165 --- /dev/null +++ b/tests/basics/try_finally_return3.py @@ -0,0 +1,103 @@ +# test 'return' within the finally block, with nested finally's +# only inactive finally's should be executed, and only once + +# basic nested finally's, the print should only be executed once +def f(): + try: + raise TypeError + finally: + print(1) + try: + raise ValueError + finally: + return 42 +print(f()) + +# similar to above but more nesting +def f(): + try: + raise ValueError + finally: + print(1) + try: + raise TypeError + finally: + print(2) + try: + pass + finally: + return 42 +print(f()) + +# similar to above but even more nesting +def f(): + try: + raise ValueError + finally: + print(1) + try: + raise TypeError + finally: + print(2) + try: + raise Exception + finally: + print(3) + return 42 +print(f()) + +# upon return some try's are active, some finally's are active, some inactive +def f(): + try: + try: + pass + finally: + print(2) + return 42 + finally: + print(1) +print(f()) + +# same as above but raise instead of pass +def f(): + try: + try: + raise ValueError + finally: + print(2) + return 42 + finally: + print(1) +print(f()) + +# upon return exception stack holds: active finally, inactive finally, active finally +def f(): + try: + raise Exception + finally: + print(1) + try: + try: + pass + finally: + print(3) + return 42 + finally: + print(2) +print(f()) + +# same as above but raise instead of pass in innermost try block +def f(): + try: + raise Exception + finally: + print(1) + try: + try: + raise Exception + finally: + print(3) + return 42 + finally: + print(2) +print(f()) diff --git a/tests/basics/try_finally_return4.py b/tests/basics/try_finally_return4.py new file mode 100644 index 0000000000000..8b54fe92ce4f6 --- /dev/null +++ b/tests/basics/try_finally_return4.py @@ -0,0 +1,83 @@ +# test try-finally with return, where unwinding return has to go through +# another try-finally which may affect the behaviour of the return + +# case where a simple try-finally executes during an unwinding return +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + finally: + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) + +# case where an unwinding return is replaced by another one +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + return 43 + finally: + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) + +# case where an unwinding return is cancelled by an exception +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + raise ValueError # cancels any active return + finally: + print(2) + print(3) + print(4) + finally: + print(5) +try: + print(f(0)) +except: + print('caught') +try: + print(f(1)) +except: + print('caught') + +# case where an unwinding return is cancelled then resumed +def f(x): + try: + try: + if x: + return 42 + finally: + try: + print(1) + raise Exception # cancels any active return + except: # cancels the exception and resumes any active return + print(2) + print(3) + print(4) + finally: + print(5) +print(f(0)) +print(f(1)) diff --git a/tests/basics/with_raise.py b/tests/basics/with_raise.py new file mode 100644 index 0000000000000..67eab09b41fb3 --- /dev/null +++ b/tests/basics/with_raise.py @@ -0,0 +1,44 @@ +# test with when context manager raises in __enter__/__exit__ + +class CtxMgr: + def __init__(self, id): + self.id = id + + def __enter__(self): + print("__enter__", self.id) + if 10 <= self.id < 20: + raise Exception('enter', self.id) + return self + + def __exit__(self, a, b, c): + print("__exit__", self.id, repr(a), repr(b)) + if 15 <= self.id < 25: + raise Exception('exit', self.id) + +# no raising +try: + with CtxMgr(1): + pass +except Exception as e: + print(e) + +# raise in enter +try: + with CtxMgr(10): + pass +except Exception as e: + print(e) + +# raise in enter and exit +try: + with CtxMgr(15): + pass +except Exception as e: + print(e) + +# raise in exit +try: + with CtxMgr(20): + pass +except Exception as e: + print(e) diff --git a/tests/bench/arrayop-1-list_inplace.py b/tests/bench/arrayop-1-list_inplace.py index 0ee1ef2ecac3e..b29593c1a1f39 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 9d5095c53a58f..5959d3f4692d9 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 a6d62807057d2..fbbade2cac3de 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 1b92a4096137f..8fa987970594e 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 0cd40a93fccd8..d7087e0e09199 100644 --- a/tests/bench/bench.py +++ b/tests/bench/bench.py @@ -3,6 +3,7 @@ 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 4a4bbc6fae900..8b8120a530275 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 786a80462259c..8d6b5d52892cd 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 7e7d9391cc93d..e1b6016a5713a 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 daa622991f004..9ecee479783d1 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 078d08e99b076..2752d4e784b3d 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 d209daecc5fdc..384d52903fe9f 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 be019c52feec8..98e22d68138b8 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 7b7fa36c6eb66..f052f6deeadd2 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 7c7f134c8531e..ff9d1b4df5efd 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 b793a3207e431..967cb99eea2be 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 20aa556277000..b85501916024d 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 72001a05c7ebc..d0c4c65a7436f 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 e2263b8ef907d..aec2e65adfa25 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 eee0ea8289683..cadb17768c5ba 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 7e03ee2f853c3..12010d0150bec 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 1fa0fbda59c5f..4dc5650902a0b 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 7bc81e5bea44d..18252570c116b 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 7f95106841407..deac15cb41ade 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 20935164e847f..c7c148df102a6 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 6c5e44419c0fa..a25ab241c66d3 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 fbeb79630db1a..8c3f0ccd597cb 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 d5c36c60aab69..a245258040be8 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 1a6d728c63455..d922888685984 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 e22adf6cbe86b..fdb11eaac63cf 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 fe4a3857e19a4..4189bf329d3bb 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 1ab8054a0fe8f..22c64403bfa4f 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 de8dee2ca9c60..47b004c2bda6d 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 b9a1af414b5a6..419c817c8fbb1 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 96bdb9129f3a5..d25102a6304cc 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 eec977909cd08..4a24194725b78 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 5758ad61aafd9..a47240d64658e 100644 --- a/tests/bench/var-2-global.py +++ b/tests/bench/var-2-global.py @@ -2,9 +2,11 @@ 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 124b484295220..182bb95f6ff74 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 cf050c58fdeeb..b9734357c8528 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 02ae874ac2efc..e10770ee5bba0 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 787ed870fb3d0..0124ef51b3022 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 e8d338360567b..692cef20dfb20 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 @@ def __init__(self): 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 f9d463f40af89..2ed7800be5cbe 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 90ae7209d881d..e3a2fa19cd32e 100644 --- a/tests/bench/var-8-namedtuple-1st.py +++ b/tests/bench/var-8-namedtuple-1st.py @@ -3,10 +3,12 @@ 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 0d5789d2ed04a..3e52121746673 100644 --- a/tests/bench/var-8.1-namedtuple-5th.py +++ b/tests/bench/var-8.1-namedtuple-5th.py @@ -3,10 +3,12 @@ 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 new file mode 100644 index 0000000000000..8b40e916dc8cf --- /dev/null +++ b/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py @@ -0,0 +1,35 @@ +import audiocore +import audiobusio +import board +import digitalio +import array +import time +import math +import rp2pio +import adafruit_pioasm + +time.sleep(10) + +trigger = digitalio.DigitalInOut(board.D4) +trigger.switch_to_output(True) + +# Generate one period of sine wav. +length = 8000 // 440 + +# signed 16 bit +s16 = array.array("h", [0] * length) +for i in range(length): + s16[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 15)) + print(s16[i]) + +sample = audiocore.RawSample(s16, sample_rate=8000) + +dac = audiobusio.I2SOut(bit_clock=board.D10, word_select=board.D11, data=board.D12) + +trigger.value = False +dac.play(sample, loop=True) +time.sleep(1) +dac.stop() +trigger.value = True + +print("done") diff --git a/tests/circuitpython-manual/audiobusio/pdmin_rms.py b/tests/circuitpython-manual/audiobusio/pdmin_rms.py new file mode 100644 index 0000000000000..53a6fea156213 --- /dev/null +++ b/tests/circuitpython-manual/audiobusio/pdmin_rms.py @@ -0,0 +1,43 @@ +import audiobusio +import board +import digitalio +import array +import time +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) + + return math.sqrt(samples_sum / len(values)) + + +# signed 16 bit +s16 = array.array("H", [0] * 10000) + +pdm = audiobusio.PDMIn(clock_pin=board.D11, data_pin=board.D12, sample_rate=24000, bit_depth=16) + +print("starting read") +trigger.value = False +count = pdm.record(s16, len(s16)) +trigger.value = True +print("read done") +print("recorded {} samples".format(count)) +for v in s16[:count]: + print(v) + + +magnitude = normalized_rms(s16) +print("magnitude", magnitude) + +print("count", count) + +print("done") diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-16bit-mono-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-16bit-mono-signed.wav new file mode 100644 index 0000000000000..cd3da395bd6ea Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-16bit-mono-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-16bit-stereo-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-16bit-stereo-signed.wav new file mode 100644 index 0000000000000..c1036475b865e Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-16bit-stereo-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-24bit-mono-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-24bit-mono-signed.wav new file mode 100644 index 0000000000000..6aa6afc7ab4f6 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-24bit-mono-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-24bit-stereo-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-24bit-stereo-signed.wav new file mode 100644 index 0000000000000..c175aaf612559 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-24bit-stereo-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-8bit-mono-unsigned.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-8bit-mono-unsigned.wav new file mode 100644 index 0000000000000..ccf63b9c1518d Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-8bit-mono-unsigned.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-8bit-stereo-unsigned.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-8bit-stereo-unsigned.wav new file mode 100644 index 0000000000000..63aaa5b29440f Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-16000-8bit-stereo-unsigned.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-16bit-mono-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-16bit-mono-signed.wav new file mode 100644 index 0000000000000..147b14b169b00 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-16bit-mono-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-16bit-stereo-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-16bit-stereo-signed.wav new file mode 100644 index 0000000000000..adfe84fb0315f Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-16bit-stereo-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-24bit-mono-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-24bit-mono-signed.wav new file mode 100644 index 0000000000000..2c5337045d3aa Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-24bit-mono-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-24bit-stereo-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-24bit-stereo-signed.wav new file mode 100644 index 0000000000000..a290c6c379b07 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-24bit-stereo-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-8bit-mono-unsigned.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-8bit-mono-unsigned.wav new file mode 100644 index 0000000000000..cd1c79280ac33 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-8bit-mono-unsigned.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-8bit-stereo-unsigned.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-8bit-stereo-unsigned.wav new file mode 100644 index 0000000000000..12c48e2583c93 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-8bit-stereo-unsigned.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-stereo.mp3 b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-stereo.mp3 new file mode 100644 index 0000000000000..fd820e69acde6 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-44100-stereo.mp3 differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-16bit-mono-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-16bit-mono-signed.wav new file mode 100644 index 0000000000000..a730c2b84c50b Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-16bit-mono-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-16bit-stereo-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-16bit-stereo-signed.wav new file mode 100644 index 0000000000000..5038ae8ae50a3 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-16bit-stereo-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-24bit-mono-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-24bit-mono-signed.wav new file mode 100644 index 0000000000000..ac25cddb37db3 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-24bit-mono-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-24bit-stereo-signed.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-24bit-stereo-signed.wav new file mode 100644 index 0000000000000..6fec674312ecc Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-24bit-stereo-signed.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-8bit-mono-unsigned.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-8bit-mono-unsigned.wav new file mode 100644 index 0000000000000..d5e49b24b3993 Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-8bit-mono-unsigned.wav differ diff --git a/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-8bit-stereo-unsigned.wav b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-8bit-stereo-unsigned.wav new file mode 100644 index 0000000000000..3df7945aa2f0a Binary files /dev/null and b/tests/circuitpython-manual/audiocore/jeplayer-splash-8000-8bit-stereo-unsigned.wav differ diff --git a/tests/circuitpython-manual/audiocore/single-track.midi b/tests/circuitpython-manual/audiocore/single-track.midi new file mode 100755 index 0000000000000..3b3dcea8221ff Binary files /dev/null and b/tests/circuitpython-manual/audiocore/single-track.midi differ diff --git a/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py b/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py new file mode 100644 index 0000000000000..6013892a95078 --- /dev/null +++ b/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py @@ -0,0 +1,60 @@ +import audiocore +import audiopwmio +import board +import digitalio +import array +import time +import math + +trigger = digitalio.DigitalInOut(board.D4) +trigger.switch_to_output(True) + +# Generate one period of sine wav. +length = 8000 // 440 + +samples = [] +sample_names = ["unsigned 8 bit", "signed 8 bit", "unsigned 16 bit", "signed 16 bit"] + + +# unsigned 8 bit +u8 = array.array("B", [0] * length) +for i in range(length): + u8[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 7) + 2 ** 7) + +samples.append(audiocore.RawSample(u8, sample_rate=4000)) + +# signed 8 bit +s8 = array.array("b", [0] * length) +for i in range(length): + s8[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 7)) + +samples.append(audiocore.RawSample(s8, sample_rate=16000)) + +# unsigned 16 bit +u16 = array.array("H", [0] * length) +for i in range(length): + u16[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 15) + 2 ** 15) + +samples.append(audiocore.RawSample(u16, sample_rate=8000)) + + +# signed 16 bit +s16 = array.array("h", [0] * length) +for i in range(length): + s16[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 15)) + +samples.append(audiocore.RawSample(s16, sample_rate=8000)) + + +dac = audiopwmio.PWMAudioOut(board.D13) +for sample, name in zip(samples, sample_names): + print(name) + trigger.value = False + dac.play(sample, loop=True) + time.sleep(1) + dac.stop() + time.sleep(0.1) + trigger.value = True + print() + +print("done") diff --git a/tests/circuitpython-manual/audiopwmio/wavefile_pause_resume.py b/tests/circuitpython-manual/audiopwmio/wavefile_pause_resume.py new file mode 100644 index 0000000000000..27912d321795d --- /dev/null +++ b/tests/circuitpython-manual/audiopwmio/wavefile_pause_resume.py @@ -0,0 +1,39 @@ +import audiocore +import audiopwmio +import board +import digitalio +import time +import math +import os + +trigger = digitalio.DigitalInOut(board.D4) +trigger.switch_to_output(True) + +sample_prefix = "jeplayer-splash" + +samples = [] +for fn in os.listdir("/"): + if fn.startswith(sample_prefix): + samples.append(fn) + +dac = audiopwmio.PWMAudioOut(left_channel=board.D12, right_channel=board.D13) +for filename in samples: + print("playing", filename) + with open(filename, "rb") as sample_file: + try: + sample = audiocore.WaveFile(sample_file) + except OSError as e: + print(e) + continue + trigger.value = False + dac.play(sample) + while dac.playing: + time.sleep(0.1) + dac.pause() + time.sleep(0.1) + dac.resume() + trigger.value = True + time.sleep(0.1) + print() + +print("done") diff --git a/tests/circuitpython-manual/audiopwmio/wavefile_playback.py b/tests/circuitpython-manual/audiopwmio/wavefile_playback.py new file mode 100644 index 0000000000000..0adbf2b19c353 --- /dev/null +++ b/tests/circuitpython-manual/audiopwmio/wavefile_playback.py @@ -0,0 +1,36 @@ +import audiocore +import audiopwmio +import board +import digitalio +import time +import math +import os + +trigger = digitalio.DigitalInOut(board.D4) +trigger.switch_to_output(True) + +sample_prefix = "jeplayer-splash" + +samples = [] +for fn in os.listdir("/"): + if fn.startswith(sample_prefix): + samples.append(fn) + +dac = audiopwmio.PWMAudioOut(left_channel=board.D12, right_channel=board.D13) +for filename in samples: + print("playing", filename) + with open(filename, "rb") as sample_file: + try: + sample = audiocore.WaveFile(sample_file) + except OSError as e: + print(e) + continue + trigger.value = False + dac.play(sample) + while dac.playing: + time.sleep(1) + trigger.value = True + time.sleep(0.1) + print() + +print("done") diff --git a/tests/circuitpython-manual/busio/uart_echo.py b/tests/circuitpython-manual/busio/uart_echo.py new file mode 100644 index 0000000000000..d429c7781cd54 --- /dev/null +++ b/tests/circuitpython-manual/busio/uart_echo.py @@ -0,0 +1,18 @@ +import busio +import board +import time + +i = 0 + +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 + time.sleep(0.1) + 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(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 new file mode 100644 index 0000000000000..a6e9e6b3e9753 --- /dev/null +++ b/tests/circuitpython-manual/socketpool/client/cpy-client.py @@ -0,0 +1,26 @@ +import wifi +import socketpool +import ssl +import time + +TIMEOUT = None +HOST = "192.168.10.179" +PORT = 5000 + +# Connect to wifi +print("Connecting to wifi") +wifi.radio.connect("mySSID", "myPASS") +pool = socketpool.SocketPool(wifi.radio) + +print("Creating Socket") +with pool.socket(pool.AF_INET, pool.SOCK_STREAM) as s: + s.settimeout(TIMEOUT) + + print("Connecting") + s.connect((HOST, PORT)) + print("Sending") + sent = s.send(b"Hello, world") + print("Receiving") + buff = bytearray(128) + numbytes = s.recv_into(buff) +print(repr(buff)) diff --git a/tests/circuitpython-manual/socketpool/client/host-server.py b/tests/circuitpython-manual/socketpool/client/host-server.py new file mode 100644 index 0000000000000..49da4055f936e --- /dev/null +++ b/tests/circuitpython-manual/socketpool/client/host-server.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +import socket + +TIMEOUT = 10 +HOST = "192.168.10.179" +PORT = 5000 + +print("Create Socket") +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(TIMEOUT) + s.bind((HOST, PORT)) + s.listen() + print("Accepting connections") + while True: + try: + conn, addr = s.accept() + break + except BlockingIOError: + pass + + with conn: + s.settimeout(TIMEOUT) + print("Connected by", addr) + data = conn.recv(128) + print("got: " + str(data)) + conn.sendall(data) + print("sent: " + str(data)) diff --git a/tests/circuitpython-manual/socketpool/client/readme.md b/tests/circuitpython-manual/socketpool/client/readme.md new file mode 100644 index 0000000000000..45cdf23c8cbb2 --- /dev/null +++ b/tests/circuitpython-manual/socketpool/client/readme.md @@ -0,0 +1,46 @@ +# Circuitpython as Client + +This example demonstrates the use of Socket as a client, accessing a server on a host development machine. This Circuitpython sketch uses the Connect, Send, and Recv_Into methods. + +## Prerequisites + +Circuitpython V6.2.0 minimum. Neither the host or client sketch has installed module prerequisites. + +## Setup + +Find a viable IP address for the host machine first and insert it in both sketches as HOST. On mac, this can be done by going to System Preferences/Network and checking the IP address used to connect to the local wireless network. Make sure that both devices are using the same WIFI! + +Each sketch can have Timeout values changed. The host sketch usually needs a value above 0, or the recv() will fail. Currently, Circuitpython's Connect function is always blocking, so changing the client timeout will not cause much change in behavior. + +Start the Server on the host PC first, within this folder: + +``` +python host-server.py +``` + +Then, reload the client sketch in Circuitpython. + +## Expected Behavior + +The example should connect to a server running on the host machine. The client will send a "Hello world" string to the server, which will return it. + +Expected client output: + +``` +Connecting to wifi +Creating Socket +Connecting +Sending +Receiving +bytearray(b'Hello, world') +``` + +Expected Server output (IP/port values will vary): + +``` +Create Socket +Accepting connections +Connected by ('192.168.10.128', 64509) +got: b'Hello, world' +sent: b'Hello, world' +``` diff --git a/tests/circuitpython-manual/socketpool/datagram/ntp.py b/tests/circuitpython-manual/socketpool/datagram/ntp.py new file mode 100644 index 0000000000000..df5fadb13878c --- /dev/null +++ b/tests/circuitpython-manual/socketpool/datagram/ntp.py @@ -0,0 +1,28 @@ +import wifi +import socketpool +import struct +import time + +# connect to wifi +print("Connecting to Wifi") +wifi.radio.connect("mySSID", "myPASS") +pool = socketpool.SocketPool(wifi.radio) + +# make socket +print("Creating socket") +sock = pool.socket(pool.AF_INET, pool.SOCK_DGRAM) + +# Fill packet +packet = bytearray(48) +packet[0] = 0b00100011 # Not leap second, NTP version 4, Client mode +NTP_TO_UNIX_EPOCH = 2208988800 # 1970-01-01 00:00:00 + +print("Sending packet") +sock.sendto(packet, ("pool.ntp.org", 123)) + +size, address = sock.recvfrom_into(packet) +print("Received packet") + +seconds = struct.unpack_from("!I", packet, offset=len(packet) - 8)[0] +print("Address:", address) +print("Time:", time.localtime(seconds - NTP_TO_UNIX_EPOCH)) diff --git a/tests/circuitpython-manual/socketpool/datagram/readme.md b/tests/circuitpython-manual/socketpool/datagram/readme.md new file mode 100644 index 0000000000000..f63f0abccd160 --- /dev/null +++ b/tests/circuitpython-manual/socketpool/datagram/readme.md @@ -0,0 +1,19 @@ +# Circuitpython Datagrams + +This example demonstrates using UDP (datagrams) with the Socket module, accessing the time from an NTP server using `sendto` and `recvfrom_into`. + +## Prerequisites + +Circuitpython V6.2.0 minimum. + +## Expected behavior + +The Circuitpython device will attempt to connect to wifi, and send a request for the time to `pool.ntp.org`. It will then convert the seconds returned into a unix time struct. + +Expected output: +``` +Sending packet +Received packet +Address: ('82.197.188.130', 31488) +Time: struct_time(tm_year=2021, tm_mon=2, tm_mday=11, tm_hour=22, tm_min=22, tm_sec=40, tm_wday=3, tm_yday=42, tm_isdst=-1) +``` diff --git a/tests/circuitpython-manual/socketpool/server/cpy-server.py b/tests/circuitpython-manual/socketpool/server/cpy-server.py new file mode 100644 index 0000000000000..bce1f9d6a2bb5 --- /dev/null +++ b/tests/circuitpython-manual/socketpool/server/cpy-server.py @@ -0,0 +1,31 @@ +import wifi +import socketpool + +TIMEOUT = None + +print("Connecting to Wifi") +wifi.radio.connect("mySSID", "myPASS") + +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 + +print("Creating socket") +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) + buff = bytearray(128) + print("Receiving") + numbytes = conn.recvfrom_into(buff) + print(buff[: numbytes[0]]) + if numbytes: + print("Sending") + 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 new file mode 100644 index 0000000000000..e2cc77c4e6b10 --- /dev/null +++ b/tests/circuitpython-manual/socketpool/server/host-client.py @@ -0,0 +1,17 @@ +import socket + +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) + + print("Connecting") + s.connect((HOST, PORT)) + + print("Sending") + s.send(b"Hello, world") + + print("Receiving") + data = s.recv(1024) + print("Received", repr(data)) diff --git a/tests/circuitpython-manual/socketpool/server/readme.md b/tests/circuitpython-manual/socketpool/server/readme.md new file mode 100644 index 0000000000000..26118b8f12487 --- /dev/null +++ b/tests/circuitpython-manual/socketpool/server/readme.md @@ -0,0 +1,43 @@ +# Circuitpython as Client + +This example demonstrates the use of Socket as a server, accessed by a client program on a host development machine. This Circuitpython sketch uses the Bind, Listen, Accept, and recvfrom_into calls. + +## Prerequisites + +Circuitpython V6.2.0 minimum. Neither the host or client sketch has installed module prerequisites. + +## Setup + +Make sure that both devices are using the same WIFI! The Circuitpython Server will automatically pick an IP and print it over the CDC monitor. Copy this value into the host client sketch. Start the Server on Circuitpython first, then run the client sketch in this folder: + +``` +python host-client.py +``` + +Each sketch can have Timeout values changed. + +## Expected behavior + +The host machine will connect to the server running on the Circuitpython device, and send a "Hello, world" string which is then returned. + +Expected client output: + +``` +Connecting +Sending +Receiving +Received b'Hello, world' +``` + +Expected server output: +``` +Connecting to Wifi +Finding IP address +192.168.10.128 +Creating socket +Accepting connections +Connected by ('192.168.10.179', 33274) +Receiving +bytearray(b'Hello, world') +Sending +``` diff --git a/tests/circuitpython/nvm_not_present.py b/tests/circuitpython/nvm_not_present.py index 141e60b01e37c..53ad3ada5b50a 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 bef80dcc61441..ceaadc60bf1b4 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 da36c80703ce5..50da369543a31 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 6e99fc418905b..326f2373f6542 100644 --- a/tests/cmdline/cmd_showbc.py +++ b/tests/cmdline/cmd_showbc.py @@ -1,5 +1,7 @@ # cmdline: -v -v # test printing of all bytecodes +# fmt: off + def f(): # constants @@ -14,9 +16,9 @@ def f(): c = [1, 2] d = {1, 2} e = {} - f = {1:2} - g = 'a' - h = b'a' + f = {1: 2} + g = "a" + h = b"a" # unary/binary ops i = 1 @@ -58,7 +60,7 @@ def f(): # comprehensions a = (b for c in d if e) a = [b for c in d if e] - a = {b:b for c in d if e} + a = {b: b for c in d if e} # function calls a() @@ -107,7 +109,9 @@ def f(): # closed over variables x = 1 + def closure(): + nonlocal x a = x + 1 x = 1 del x @@ -125,12 +129,14 @@ def closure(): return return 1 + # function with lots of locals def f(): l1 = l2 = l3 = l4 = l5 = l6 = l7 = l8 = l9 = l10 = 1 m1 = m2 = m3 = m4 = m5 = m6 = m7 = m8 = m9 = m10 = 2 l10 + m10 + # functions with default args def f(a=1): pass @@ -138,16 +144,19 @@ def f(a=1): def f(b=2): return b + a + # function which yields def f(): yield yield 1 yield from 1 + # class class Class: pass + # delete name del Class diff --git a/tests/cmdline/cmd_showbc.py.exp b/tests/cmdline/cmd_showbc.py.exp index 1274cda00f59e..ac4cedd340a6f 100644 --- a/tests/cmdline/cmd_showbc.py.exp +++ b/tests/cmdline/cmd_showbc.py.exp @@ -7,7 +7,7 @@ arg names: (N_EXC_STACK 0) bc=-1 line=1 ######## - bc=\\d\+ line=155 + bc=\\d\+ line=164 00 MAKE_FUNCTION \.\+ \\d\+ STORE_NAME f \\d\+ MAKE_FUNCTION \.\+ @@ -40,7 +40,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (INIT_CELL 16) bc=-4 line=1 ######## - bc=\\d\+ line=126 + bc=\\d\+ line=130 00 LOAD_CONST_NONE 01 LOAD_CONST_FALSE 02 BINARY_OP 26 __add__ @@ -326,7 +326,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (N_EXC_STACK 0) bc=-1 line=1 ######## - bc=\\d\+ line=132 + bc=\\d\+ line=137 00 LOAD_CONST_SMALL_INT 1 01 DUP_TOP 02 STORE_FAST 0 @@ -382,7 +382,7 @@ arg names: a (N_EXC_STACK 0) (INIT_CELL 0) ######## - bc=\\d\+ line=138 + bc=\\d\+ line=144 00 LOAD_CONST_SMALL_INT 2 01 BUILD_TUPLE 1 03 LOAD_NULL @@ -399,9 +399,9 @@ arg names: (N_STATE 2) (N_EXC_STACK 0) bc=-1 line=1 - bc=0 line=143 - bc=3 line=144 - bc=6 line=145 + bc=0 line=150 + bc=3 line=151 + bc=6 line=152 00 LOAD_CONST_NONE 01 YIELD_VALUE 02 POP_TOP @@ -423,7 +423,7 @@ arg names: (N_STATE 1) (N_EXC_STACK 0) bc=-1 line=1 - bc=13 line=149 + bc=13 line=157 00 LOAD_NAME __name__ (cache=0) 04 STORE_NAME __module__ 07 LOAD_CONST_STRING 'Class' @@ -438,7 +438,7 @@ arg names: self (N_STATE 4) (N_EXC_STACK 0) bc=-1 line=1 - bc=0 line=156 + bc=0 line=165 00 LOAD_GLOBAL super (cache=0) \\d\+ LOAD_GLOBAL __class__ (cache=0) \\d\+ LOAD_FAST 0 @@ -518,7 +518,7 @@ arg names: * (N_EXC_STACK 0) bc=-\\d\+ line=1 ######## - bc=\\d\+ line=113 + bc=\\d\+ line=117 00 LOAD_DEREF 0 02 LOAD_CONST_SMALL_INT 1 03 BINARY_OP 26 __add__ @@ -537,7 +537,7 @@ arg names: * b (N_EXC_STACK 0) bc=-\\d\+ line=1 ######## - bc=\\d\+ line=139 + bc=\\d\+ line=145 00 LOAD_FAST 1 01 LOAD_DEREF 0 03 BINARY_OP 26 __add__ diff --git a/tests/cpydiff/core_class_delnotimpl.py b/tests/cpydiff/core_class_delnotimpl.py index c51c3d536f686..18c176e9bb1f7 100644 --- a/tests/cpydiff/core_class_delnotimpl.py +++ b/tests/cpydiff/core_class_delnotimpl.py @@ -6,9 +6,11 @@ """ 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 99713e790c4df..bdd6dd5df6b8f 100644 --- a/tests/cpydiff/core_class_mro.py +++ b/tests/cpydiff/core_class_mro.py @@ -4,12 +4,16 @@ 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 f0823ee11dd8d..9a87b85a87c96 100644 --- a/tests/cpydiff/core_class_supermultiple.py +++ b/tests/cpydiff/core_class_supermultiple.py @@ -4,24 +4,29 @@ 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 297293908427d..a8380c690aa99 100644 --- a/tests/cpydiff/core_function_userattr.py +++ b/tests/cpydiff/core_function_userattr.py @@ -4,8 +4,11 @@ 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 c25fbe75a2615..149e9a0a90bcf 100644 --- a/tests/cpydiff/core_generator_noexit.py +++ b/tests/cpydiff/core_generator_noexit.py @@ -4,11 +4,15 @@ 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 4a71217821274..3ce2340c68dc7 100644 --- a/tests/cpydiff/core_import_prereg.py +++ b/tests/cpydiff/core_import_prereg.py @@ -12,6 +12,7 @@ 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 700620c4701b0..62bf337a22bfa 100644 --- a/tests/cpydiff/core_import_split_ns_pkgs.py +++ b/tests/cpydiff/core_import_split_ns_pkgs.py @@ -5,6 +5,7 @@ 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 0240e5a1a9f9d..af3280c6d70a7 100644 --- a/tests/cpydiff/core_locals.py +++ b/tests/cpydiff/core_locals.py @@ -4,8 +4,11 @@ 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 8416e3b069142..025d226372986 100644 --- a/tests/cpydiff/core_locals_eval.py +++ b/tests/cpydiff/core_locals_eval.py @@ -6,9 +6,11 @@ """ 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 e6e33a7b462ea..51cd4b2490c17 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 190a3c2760494..8f25b0d49149d 100644 --- a/tests/cpydiff/modules_array_containment.py +++ b/tests/cpydiff/modules_array_containment.py @@ -5,4 +5,5 @@ 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 97f988da23410..3376527373edf 100644 --- a/tests/cpydiff/modules_array_deletion.py +++ b/tests/cpydiff/modules_array_deletion.py @@ -5,6 +5,7 @@ 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 1103f18269dc6..24308bd9042d1 100644 --- a/tests/cpydiff/modules_array_subscrstep.py +++ b/tests/cpydiff/modules_array_subscrstep.py @@ -5,5 +5,6 @@ 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 a503ea4f55be3..4d2746d1f864e 100644 --- a/tests/cpydiff/modules_deque.py +++ b/tests/cpydiff/modules_deque.py @@ -5,5 +5,6 @@ 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 913b734e8bd26..ffe523786f501 100644 --- a/tests/cpydiff/modules_json_nonserializable.py +++ b/tests/cpydiff/modules_json_nonserializable.py @@ -5,10 +5,11 @@ 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 08d32ca672764..cb6b0fd874ec4 100644 --- a/tests/cpydiff/modules_struct_fewargs.py +++ b/tests/cpydiff/modules_struct_fewargs.py @@ -5,8 +5,9 @@ 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 cdbb5c672c111..03395baad3b59 100644 --- a/tests/cpydiff/modules_struct_manyargs.py +++ b/tests/cpydiff/modules_struct_manyargs.py @@ -5,8 +5,9 @@ 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 1bf2a598a0db9..7d086078a93d6 100644 --- a/tests/cpydiff/modules_sys_stdassign.py +++ b/tests/cpydiff/modules_sys_stdassign.py @@ -5,5 +5,6 @@ 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 8578a51e28526..c308240a78da5 100644 --- a/tests/cpydiff/syntax_spaces.py +++ b/tests/cpydiff/syntax_spaces.py @@ -5,14 +5,14 @@ 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_format.py b/tests/cpydiff/types_bytes_format.py new file mode 100644 index 0000000000000..ad0498771165c --- /dev/null +++ b/tests/cpydiff/types_bytes_format.py @@ -0,0 +1,7 @@ +""" +categories: Types,bytes +description: bytes objects support .format() method +cause: MicroPython strives to be a more regular implementation, so if both `str` and `bytes` support ``__mod__()`` (the % operator), it makes sense to support ``format()`` for both too. Support for ``__mod__`` can also be compiled out, which leaves only ``format()`` for bytes formatting. +workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects. +""" +print(b"{}".format(1)) diff --git a/tests/cpydiff/types_bytes_keywords.py b/tests/cpydiff/types_bytes_keywords.py index 4dc383f2627b7..550ce12bbd882 100644 --- a/tests/cpydiff/types_bytes_keywords.py +++ b/tests/cpydiff/types_bytes_keywords.py @@ -4,4 +4,4 @@ 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 2871bda6c17ef..51b94cb710f1c 100644 --- a/tests/cpydiff/types_bytes_subscrstep.py +++ b/tests/cpydiff/types_bytes_subscrstep.py @@ -4,4 +4,4 @@ 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 39cdaf45b80bd..ade9ebc7ab964 100644 --- a/tests/cpydiff/types_exception_subclassinit.py +++ b/tests/cpydiff/types_exception_subclassinit.py @@ -8,8 +8,11 @@ class A(Exception): 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 c8d3cfbe882ad..a5b591966b0de 100644 --- a/tests/cpydiff/types_float_rounding.py +++ b/tests/cpydiff/types_float_rounding.py @@ -4,4 +4,4 @@ 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 260b060ed6250..5d337412c7f53 100644 --- a/tests/cpydiff/types_int_subclassconv.py +++ b/tests/cpydiff/types_int_subclassconv.py @@ -4,8 +4,11 @@ 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 ac2600bd252c7..f222ac1cd3ad3 100644 --- a/tests/cpydiff/types_str_endswith.py +++ b/tests/cpydiff/types_str_endswith.py @@ -4,4 +4,4 @@ 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 dd1d8d33d7450..1b83cfff6cd34 100644 --- a/tests/cpydiff/types_str_formatsubscr.py +++ b/tests/cpydiff/types_str_formatsubscr.py @@ -4,4 +4,4 @@ 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 b336b1a73e2e6..77a4eac1c1db2 100644 --- a/tests/cpydiff/types_str_keywords.py +++ b/tests/cpydiff/types_str_keywords.py @@ -4,4 +4,4 @@ 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 fa3f594c1fef4..72e5105e025b2 100644 --- a/tests/cpydiff/types_str_ljust_rjust.py +++ b/tests/cpydiff/types_str_ljust_rjust.py @@ -4,4 +4,4 @@ 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 cadf8698779af..5d334fea2f846 100644 --- a/tests/cpydiff/types_str_rsplitnone.py +++ b/tests/cpydiff/types_str_rsplitnone.py @@ -4,4 +4,4 @@ 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 8aec1ea78fd5d..e44198fccf741 100644 --- a/tests/cpydiff/types_str_subclassequality.py +++ b/tests/cpydiff/types_str_subclassequality.py @@ -4,8 +4,11 @@ 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 0c2fce1b11bd9..2d3245e5582f5 100644 --- a/tests/cpydiff/types_str_subscrstep.py +++ b/tests/cpydiff/types_str_subscrstep.py @@ -4,4 +4,4 @@ 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 59638ef0a467b..4890d92b4202c 100644 --- a/tests/extmod/btree1.py +++ b/tests/extmod/btree1.py @@ -6,7 +6,7 @@ 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 2c13665228a6a..c8e0132265aa0 100644 --- a/tests/extmod/framebuf1.py +++ b/tests/extmod/framebuf1.py @@ -8,9 +8,11 @@ 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 @@ # 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 @@ 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 fe81f7f93f8c0..e658f1345ad1a 100644 --- a/tests/extmod/framebuf16.py +++ b/tests/extmod/framebuf16.py @@ -4,28 +4,30 @@ 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 @@ def printbuf(): # scroll fbuf.fill(0x0000) -fbuf.pixel(2, 2, 0xffff) +fbuf.pixel(2, 2, 0xFFFF) printbuf() fbuf.scroll(0, 1) printbuf() @@ -48,11 +50,11 @@ def printbuf(): 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 a313170eb5e42..097057fe96fa1 100644 --- a/tests/extmod/framebuf2.py +++ b/tests/extmod/framebuf2.py @@ -4,14 +4,16 @@ 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 8358fa55b9f2b..56593ee15524c 100644 --- a/tests/extmod/framebuf4.py +++ b/tests/extmod/framebuf4.py @@ -4,50 +4,52 @@ 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 b6899aae9122c..a3ca6fcd4fa8e 100644 --- a/tests/extmod/framebuf8.py +++ b/tests/extmod/framebuf8.py @@ -4,14 +4,16 @@ 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 @@ def 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 6363c224fbb52..b429776bc2881 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 @@ def __init__(self, n): 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/machine1.py b/tests/extmod/machine1.py deleted file mode 100644 index 6ff38cc05179d..0000000000000 --- a/tests/extmod/machine1.py +++ /dev/null @@ -1,28 +0,0 @@ -# test machine module - -try: - try: - import umachine as machine - except ImportError: - import machine - machine.mem8 -except: - print("SKIP") - raise SystemExit - -print(machine.mem8) - -try: - machine.mem16[1] -except ValueError: - print("ValueError") - -try: - machine.mem16[1] = 1 -except ValueError: - print("ValueError") - -try: - del machine.mem8[0] -except TypeError: - print("TypeError") diff --git a/tests/extmod/machine1.py.exp b/tests/extmod/machine1.py.exp deleted file mode 100644 index bb421ea5cfa42..0000000000000 --- a/tests/extmod/machine1.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -<8-bit memory> -ValueError -ValueError -TypeError diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py deleted file mode 100644 index e91775504d59a..0000000000000 --- a/tests/extmod/machine_pinbase.py +++ /dev/null @@ -1,30 +0,0 @@ -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase -except AttributeError: - print("SKIP") - raise SystemExit - - -class MyPin(machine.PinBase): - - def __init__(self): - print("__init__") - self.v = False - - def value(self, v=None): - print("value:", v) - if v is None: - self.v = not self.v - return int(self.v) - -p = MyPin() - -print(p.value()) -print(p.value()) -print(p.value()) -p.value(1) -p.value(0) diff --git a/tests/extmod/machine_pinbase.py.exp b/tests/extmod/machine_pinbase.py.exp deleted file mode 100644 index b31cd983088b4..0000000000000 --- a/tests/extmod/machine_pinbase.py.exp +++ /dev/null @@ -1,9 +0,0 @@ -__init__ -value: None -1 -value: None -0 -value: None -1 -value: 1 -value: 0 diff --git a/tests/extmod/machine_pulse.py b/tests/extmod/machine_pulse.py deleted file mode 100644 index d525974e0c2a9..0000000000000 --- a/tests/extmod/machine_pulse.py +++ /dev/null @@ -1,46 +0,0 @@ -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.time_pulse_us -except AttributeError: - print("SKIP") - raise SystemExit - - -class ConstPin(machine.PinBase): - - def __init__(self, value): - self.v = value - - def value(self, v=None): - if v is None: - return self.v - else: - self.v = v - - -class TogglePin(machine.PinBase): - - def __init__(self): - self.v = 0 - - def value(self, v=None): - if v is None: - self.v = 1 - self.v - print("value:", self.v) - return self.v - - -p = TogglePin() - -t = machine.time_pulse_us(p, 1) -print(type(t)) -t = machine.time_pulse_us(p, 0) -print(type(t)) - -p = ConstPin(0) -print(machine.time_pulse_us(p, 1, 10)) -print(machine.time_pulse_us(p, 0, 10)) diff --git a/tests/extmod/machine_pulse.py.exp b/tests/extmod/machine_pulse.py.exp deleted file mode 100644 index 20d4c10431938..0000000000000 --- a/tests/extmod/machine_pulse.py.exp +++ /dev/null @@ -1,9 +0,0 @@ -value: 1 -value: 0 - -value: 1 -value: 0 -value: 1 - --2 --1 diff --git a/tests/extmod/machine_signal.py b/tests/extmod/machine_signal.py deleted file mode 100644 index 53f4f5890c3dd..0000000000000 --- a/tests/extmod/machine_signal.py +++ /dev/null @@ -1,39 +0,0 @@ -# test machine.Signal class - -try: - import umachine as machine -except ImportError: - import machine -try: - machine.PinBase - machine.Signal -except AttributeError: - print("SKIP") - raise SystemExit - -class Pin(machine.PinBase): - def __init__(self): - self.v = 0 - - def value(self, v=None): - if v is None: - return self.v - else: - self.v = int(v) - - -# test non-inverted -p = Pin() -s = machine.Signal(p) -s.value(0) -print(p.value(), s.value()) -s.value(1) -print(p.value(), s.value()) - -# test inverted, and using on/off methods -p = Pin() -s = machine.Signal(p, invert=True) -s.off() -print(p.value(), s.value()) -s.on() -print(p.value(), s.value()) diff --git a/tests/extmod/machine_signal.py.exp b/tests/extmod/machine_signal.py.exp deleted file mode 100644 index 7e9dd67966873..0000000000000 --- a/tests/extmod/machine_signal.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -0 0 -1 1 -1 0 -0 1 diff --git a/tests/extmod/time_ms_us.py b/tests/extmod/time_ms_us.py index 135cf1e0967d6..0e4749b898223 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 5e642ec515a8f..c65d69ddbeb47 100644 --- a/tests/extmod/ubinascii_a2b_base64.py +++ b/tests/extmod/ubinascii_a2b_base64.py @@ -7,43 +7,43 @@ 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("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 283c3936d3dbc..8c63b545a3bac 100644 --- a/tests/extmod/ubinascii_b2a_base64.py +++ b/tests/extmod/ubinascii_b2a_base64.py @@ -7,20 +7,20 @@ 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 a826662f116c2..186bd699ae67c 100644 --- a/tests/extmod/ubinascii_crc32.py +++ b/tests/extmod/ubinascii_crc32.py @@ -13,16 +13,16 @@ 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 dabc3c7e4ca8a..3dcf0c4271d33 100644 --- a/tests/extmod/ubinascii_hexlify.py +++ b/tests/extmod/ubinascii_hexlify.py @@ -7,11 +7,11 @@ 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 77084ec9ee25f..94e8daa557b77 100644 --- a/tests/extmod/ubinascii_micropython.py +++ b/tests/extmod/ubinascii_micropython.py @@ -8,8 +8,8 @@ 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 41a1bd1b8f4a9..f656bcd758fda 100644 --- a/tests/extmod/ubinascii_unhexlify.py +++ b/tests/extmod/ubinascii_unhexlify.py @@ -7,20 +7,20 @@ 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/ucryptolib_aes128_cbc.py b/tests/extmod/ucryptolib_aes128_cbc.py new file mode 100644 index 0000000000000..d861d2c6bf47c --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_cbc.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 2, b"5678" * 4) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 4, 2, b"5678" * 4) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes128_cbc.py.exp b/tests/extmod/ucryptolib_aes128_cbc.py.exp new file mode 100644 index 0000000000000..cc73553b2aeaf --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_cbc.py.exp @@ -0,0 +1,2 @@ +b'\x1d\x84\xfa\xaa%\x0e9\x143\x8b6\xf8\xdf^yh\xd0\x94g\xf4\xcf\x1d\xa0I)\x8a\xa0\x00u0+C' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes128_ecb.py b/tests/extmod/ucryptolib_aes128_ecb.py new file mode 100644 index 0000000000000..5c0e179986822 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 4, 1) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes128_ecb.py.exp b/tests/extmod/ucryptolib_aes128_ecb.py.exp new file mode 100644 index 0000000000000..b0fd15b4472f8 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb.py.exp @@ -0,0 +1,2 @@ +b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py b/tests/extmod/ucryptolib_aes128_ecb_enc.py new file mode 100644 index 0000000000000..1d4484b0bc11e --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py @@ -0,0 +1,17 @@ +# This tests minimal configuration of ucrypto module, which is +# AES128 encryption (anything else, including AES128 decryption, +# is optional). +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp b/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp new file mode 100644 index 0000000000000..9921d4b83a7e1 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py.exp @@ -0,0 +1 @@ +b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe' diff --git a/tests/extmod/ucryptolib_aes128_ecb_inpl.py b/tests/extmod/ucryptolib_aes128_ecb_inpl.py new file mode 100644 index 0000000000000..88ccb02daf265 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_inpl.py @@ -0,0 +1,15 @@ +# Inplace operations (input and output buffer is the same) +try: + from ucryptolib import aes +except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +buf = bytearray(bytes(range(32))) +crypto.encrypt(buf, buf) +print(buf) + +crypto = aes(b"1234" * 4, 1) +crypto.decrypt(buf, buf) +print(buf) diff --git a/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp b/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp new file mode 100644 index 0000000000000..b7f7bf540922f --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_inpl.py.exp @@ -0,0 +1,2 @@ +bytearray(b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe') +bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f') diff --git a/tests/extmod/ucryptolib_aes128_ecb_into.py b/tests/extmod/ucryptolib_aes128_ecb_into.py new file mode 100644 index 0000000000000..ff832d7ef3b07 --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_into.py @@ -0,0 +1,16 @@ +# Operations with pre-allocated output buffer +try: + from ucryptolib import aes +except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 4, 1) +enc = bytearray(32) +crypto.encrypt(bytes(range(32)), enc) +print(enc) + +crypto = aes(b"1234" * 4, 1) +dec = bytearray(32) +crypto.decrypt(enc, dec) +print(dec) diff --git a/tests/extmod/ucryptolib_aes128_ecb_into.py.exp b/tests/extmod/ucryptolib_aes128_ecb_into.py.exp new file mode 100644 index 0000000000000..b7f7bf540922f --- /dev/null +++ b/tests/extmod/ucryptolib_aes128_ecb_into.py.exp @@ -0,0 +1,2 @@ +bytearray(b'Iz\xfe9\x17\xac\xa4X\x12\x04\x10\xf5K~#\xc7\xac;\xf9\xc6E\xa8\xca~\xf1\xee\xd3f%\xf1\x8d\xfe') +bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f') diff --git a/tests/extmod/ucryptolib_aes256_cbc.py b/tests/extmod/ucryptolib_aes256_cbc.py new file mode 100644 index 0000000000000..c01846f199dec --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_cbc.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 8, 2, b"5678" * 4) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 8, 2, b"5678" * 4) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes256_cbc.py.exp b/tests/extmod/ucryptolib_aes256_cbc.py.exp new file mode 100644 index 0000000000000..51262db9c6ab7 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_cbc.py.exp @@ -0,0 +1,2 @@ +b'\xb4\x0b\xff\xdd\xfc\xb5\x03\x88[m\xc1\x01+:\x03M\x18\xb03\x0f\x971g\x10\xb1\x98>\x9b\x17\xb7-\xb2' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/ucryptolib_aes256_ecb.py b/tests/extmod/ucryptolib_aes256_ecb.py new file mode 100644 index 0000000000000..0760063c14c48 --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_ecb.py @@ -0,0 +1,16 @@ +try: + from Crypto.Cipher import AES + + aes = AES.new +except ImportError: + try: + from ucryptolib import aes + except ImportError: + print("SKIP") + raise SystemExit + +crypto = aes(b"1234" * 8, 1) +enc = crypto.encrypt(bytes(range(32))) +print(enc) +crypto = aes(b"1234" * 8, 1) +print(crypto.decrypt(enc)) diff --git a/tests/extmod/ucryptolib_aes256_ecb.py.exp b/tests/extmod/ucryptolib_aes256_ecb.py.exp new file mode 100644 index 0000000000000..a00a4eb2f5cca --- /dev/null +++ b/tests/extmod/ucryptolib_aes256_ecb.py.exp @@ -0,0 +1,2 @@ +b'\xe2\xe0\xdd\xef\xc3\xcd\x88/!>\xf6\xa2\xef/\xd15z+`\xb2\xb2\xd7}!:V>\xeb\x19\xbf|\xea' +b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' diff --git a/tests/extmod/uctypes_32bit_intbig.py b/tests/extmod/uctypes_32bit_intbig.py index 6b4d3d76cda6b..eed36e87742af 100644 --- a/tests/extmod/uctypes_32bit_intbig.py +++ b/tests/extmod/uctypes_32bit_intbig.py @@ -10,16 +10,16 @@ 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 @@ 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 37c52388d6bac..d822faf7e8a96 100644 --- a/tests/extmod/uctypes_array_assign_le.py +++ b/tests/extmod/uctypes_array_assign_le.py @@ -10,19 +10,17 @@ # 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 a538bf9add72d..d4c27fc4b3f5a 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 @@ # 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 84dfba0e29134..f33c63b4ef959 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 @@ # 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 784209f803409..0619d31dc9e89 100644 --- a/tests/extmod/uctypes_byteat.py +++ b/tests/extmod/uctypes_byteat.py @@ -4,7 +4,7 @@ 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 2500e292787bc..d42956261589f 100644 --- a/tests/extmod/uctypes_error.py +++ b/tests/extmod/uctypes_error.py @@ -13,25 +13,31 @@ 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") + +# unsupported unary op +try: + hash(S) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_error.py.exp b/tests/extmod/uctypes_error.py.exp index 802c260d2b76a..f2e9c12f7f942 100644 --- a/tests/extmod/uctypes_error.py.exp +++ b/tests/extmod/uctypes_error.py.exp @@ -2,3 +2,4 @@ TypeError TypeError TypeError TypeError +TypeError diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py index 7df5ac0909b3a..466191c27a6fe 100644 --- a/tests/extmod/uctypes_le.py +++ b/tests/extmod/uctypes_le.py @@ -6,20 +6,21 @@ 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 +29,10 @@ 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 +74,7 @@ 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 84ff2b84cf6e2..89e9a9e0abe48 100644 --- a/tests/extmod/uctypes_le_float.py +++ b/tests/extmod/uctypes_le_float.py @@ -7,7 +7,7 @@ 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 @@ 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 acef47036d00c..1fdc658499678 100644 --- a/tests/extmod/uctypes_native_float.py +++ b/tests/extmod/uctypes_native_float.py @@ -4,17 +4,14 @@ 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 8bba03b38cebb..10477e669431a 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,21 @@ 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 +39,10 @@ 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 +83,7 @@ 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 c310238e546c2..6e0018abc7698 100644 --- a/tests/extmod/uctypes_print.py +++ b/tests/extmod/uctypes_print.py @@ -16,10 +16,10 @@ 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 056e4565060c5..5d8094ee48a79 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: @@ -22,6 +23,9 @@ S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.LITTLE_ENDIAN) +print(addr == int(S.ptr)) +print(addr == int(S.ptr2)) + print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) @@ -29,6 +33,6 @@ 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_le.py.exp b/tests/extmod/uctypes_ptr_le.py.exp index 30d159edd1bfd..92f6caa06943d 100644 --- a/tests/extmod/uctypes_ptr_le.py.exp +++ b/tests/extmod/uctypes_ptr_le.py.exp @@ -1,3 +1,5 @@ +True +True 48 49 0x3130 diff --git a/tests/extmod/uctypes_ptr_native_le.py b/tests/extmod/uctypes_ptr_native_le.py index 24508b1cb4156..8ca4d2c55cf9c 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 @@ 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 e42e06c92469f..6e52232e39eba 100644 --- a/tests/extmod/uctypes_sizeof.py +++ b/tests/extmod/uctypes_sizeof.py @@ -11,10 +11,13 @@ "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 1ba8871bdc62d..351632d76bbf5 100644 --- a/tests/extmod/uctypes_sizeof_float.py +++ b/tests/extmod/uctypes_sizeof_float.py @@ -4,5 +4,5 @@ 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_layout.py b/tests/extmod/uctypes_sizeof_layout.py new file mode 100644 index 0000000000000..2108e81502151 --- /dev/null +++ b/tests/extmod/uctypes_sizeof_layout.py @@ -0,0 +1,27 @@ +try: + import uctypes +except ImportError: + print("SKIP") + raise SystemExit + +desc = { + "f1": 0 | uctypes.UINT32, + "f2": 4 | uctypes.UINT8, +} + + +# uctypes.NATIVE is default +print(uctypes.sizeof(desc) == uctypes.sizeof(desc, uctypes.NATIVE)) + +# Here we assume that that we run on a platform with convential ABI +# (which rounds up structure size based on max alignment). For platforms +# where that doesn't hold, this tests should be just disabled in the runner. +print(uctypes.sizeof(desc, uctypes.NATIVE) > uctypes.sizeof(desc, uctypes.LITTLE_ENDIAN)) + +# When taking sizeof of instantiated structure, layout type param +# is prohibited (because structure already has its layout type). +s = uctypes.struct(0, desc, uctypes.LITTLE_ENDIAN) +try: + uctypes.sizeof(s, uctypes.LITTLE_ENDIAN) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_sizeof_layout.py.exp b/tests/extmod/uctypes_sizeof_layout.py.exp new file mode 100644 index 0000000000000..281f20856effc --- /dev/null +++ b/tests/extmod/uctypes_sizeof_layout.py.exp @@ -0,0 +1,3 @@ +True +True +TypeError diff --git a/tests/extmod/uctypes_sizeof_native.py b/tests/extmod/uctypes_sizeof_native.py index 32c740e773503..991cd25f52999 100644 --- a/tests/extmod/uctypes_sizeof_native.py +++ b/tests/extmod/uctypes_sizeof_native.py @@ -28,10 +28,13 @@ "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 diff --git a/tests/extmod/uctypes_sizeof_od.py b/tests/extmod/uctypes_sizeof_od.py new file mode 100644 index 0000000000000..2f070095b55ff --- /dev/null +++ b/tests/extmod/uctypes_sizeof_od.py @@ -0,0 +1,53 @@ +try: + from ucollections import OrderedDict + import uctypes +except ImportError: + print("SKIP") + raise SystemExit + +desc = OrderedDict( + { + # arr is array at offset 0, of UINT8 elements, array size is 2 + "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), + # 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), + "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, + }, + ), + } +) + +data = bytearray(b"01234567") + +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) + +print(uctypes.sizeof(S.arr)) +assert uctypes.sizeof(S.arr) == 2 + +print(uctypes.sizeof(S.arr2)) +assert uctypes.sizeof(S.arr2) == 2 + +print(uctypes.sizeof(S.arr3)) + +try: + print(uctypes.sizeof(S.arr3[0])) +except TypeError: + print("TypeError") + +print(uctypes.sizeof(S.arr4)) +assert uctypes.sizeof(S.arr4) == 6 + +print(uctypes.sizeof(S.sub)) +assert uctypes.sizeof(S.sub) == 1 + +# invalid descriptor +try: + print(uctypes.sizeof([])) +except TypeError: + print("TypeError") diff --git a/tests/extmod/uctypes_sizeof_od.py.exp b/tests/extmod/uctypes_sizeof_od.py.exp new file mode 100644 index 0000000000000..b35b11aa0cea9 --- /dev/null +++ b/tests/extmod/uctypes_sizeof_od.py.exp @@ -0,0 +1,7 @@ +2 +2 +4 +TypeError +6 +1 +TypeError diff --git a/tests/extmod/uhashlib_md5.py b/tests/extmod/uhashlib_md5.py new file mode 100644 index 0000000000000..07d5f3169200c --- /dev/null +++ b/tests/extmod/uhashlib_md5.py @@ -0,0 +1,21 @@ +try: + import uhashlib as hashlib +except ImportError: + try: + import hashlib + except ImportError: + # This is neither uPy, nor cPy, so must be uPy with + # uhashlib module disabled. + print("SKIP") + raise SystemExit + +try: + hashlib.md5 +except AttributeError: + # MD5 is only available on some ports + print("SKIP") + raise SystemExit + +md5 = hashlib.md5(b"hello") +md5.update(b"world") +print(md5.digest()) diff --git a/tests/extmod/uhashlib_sha1.py b/tests/extmod/uhashlib_sha1.py index 9d6427b33ff9f..a0ad8473a1cd4 100644 --- a/tests/extmod/uhashlib_sha1.py +++ b/tests/extmod/uhashlib_sha1.py @@ -16,13 +16,13 @@ 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 a793ea4930613..ad5aa124cb35e 100644 --- a/tests/extmod/uhashlib_sha256.py +++ b/tests/extmod/uhashlib_sha256.py @@ -26,20 +26,20 @@ # 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 7c1fe4e1ec149..a470bb6f71b13 100644 --- a/tests/extmod/uheapq1.py +++ b/tests/extmod/uheapq1.py @@ -17,11 +17,13 @@ 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 b1cb4a9cbcdb2..feda8a47dda42 100644 --- a/tests/extmod/ujson_dump.py +++ b/tests/extmod/ujson_dump.py @@ -20,11 +20,11 @@ # 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 6280fb11b6904..7ecf23afb6539 100644 --- a/tests/extmod/ujson_dump_iobase.py +++ b/tests/extmod/ujson_dump_iobase.py @@ -7,23 +7,25 @@ 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 + return len(buf) # dump to the user stream diff --git a/tests/extmod/ujson_dumps.py b/tests/extmod/ujson_dumps.py index d732718019ee2..bfdae62643233 100644 --- a/tests/extmod/ujson_dumps.py +++ b/tests/extmod/ujson_dumps.py @@ -11,8 +11,8 @@ 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, 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 21a388c32d097..f2aa7f249fc93 100644 --- a/tests/extmod/ujson_dumps_extra.py +++ b/tests/extmod/ujson_dumps_extra.py @@ -6,4 +6,4 @@ 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 9725ab2ddc9a5..7cec9246b82c5 100644 --- a/tests/extmod/ujson_load.py +++ b/tests/extmod/ujson_load.py @@ -9,7 +9,7 @@ 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 a277f40efcb4d..001aa4fb2c72f 100644 --- a/tests/extmod/ujson_load_readinto.py +++ b/tests/extmod/ujson_load_readinto.py @@ -2,6 +2,7 @@ # Test that json can load from any object with readinto + class Buffer: def __init__(self, data): self._data = data @@ -12,11 +13,12 @@ def readinto(self, buf): 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 adba3c068d27c..2de9cdcbc1a8a 100644 --- a/tests/extmod/ujson_loads.py +++ b/tests/extmod/ujson_loads.py @@ -7,23 +7,25 @@ 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 @@ def my_print(o): # 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 f1b8cc364c4ac..e368ca42e7369 100644 --- a/tests/extmod/ujson_loads_float.py +++ b/tests/extmod/ujson_loads_float.py @@ -7,11 +7,13 @@ print("SKIP") raise SystemExit + def my_print(o): - print('%.3f' % 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')) +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 d9f0005e1be38..7ea5ae8d6a9ab 100644 --- a/tests/extmod/umsgpack_pack.py +++ b/tests/extmod/umsgpack_pack.py @@ -20,11 +20,11 @@ # 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 57e6b26cba590..180197398f429 100644 --- a/tests/extmod/urandom_basic.py +++ b/tests/extmod/urandom_basic.py @@ -26,4 +26,4 @@ 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 f5a34e1687fe1..78e17379dc68e 100644 --- a/tests/extmod/urandom_extra.py +++ b/tests/extmod/urandom_extra.py @@ -10,10 +10,10 @@ 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 @@ 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 @@ 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,14 +66,4 @@ try: random.choice([]) except IndexError: - print('IndexError') - -print('random') -for i in range(50): - assert 0 <= random.random() < 1 - -print('uniform') -for i in range(50): - assert 0 <= random.uniform(0, 4) <= 4 - assert 2 <= random.uniform(2, 6) <= 6 - assert -2 <= random.uniform(-2, 2) <= 2 + print("IndexError") diff --git a/tests/extmod/urandom_extra_float.py b/tests/extmod/urandom_extra_float.py new file mode 100644 index 0000000000000..65918da136945 --- /dev/null +++ b/tests/extmod/urandom_extra_float.py @@ -0,0 +1,24 @@ +try: + import urandom as random +except ImportError: + try: + import random + except ImportError: + print("SKIP") + raise SystemExit + +try: + random.randint +except AttributeError: + print("SKIP") + raise SystemExit + +print("random") +for i in range(50): + assert 0 <= random.random() < 1 + +print("uniform") +for i in range(50): + assert 0 <= random.uniform(0, 4) <= 4 + assert 2 <= random.uniform(2, 6) <= 6 + assert -2 <= random.uniform(-2, 2) <= 2 diff --git a/tests/extmod/ure1.py b/tests/extmod/ure1.py index 710720c8b6519..d1cb9a05d9adb 100644 --- a/tests/extmod/ure1.py +++ b/tests/extmod/ure1.py @@ -83,11 +83,16 @@ 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 @@ 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 cfb264bb6d290..4cef4c98ae096 100644 --- a/tests/extmod/ure_debug.py +++ b/tests/extmod/ure_debug.py @@ -5,4 +5,4 @@ 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 f52f735c7fa5e..a99a47f97e923 100644 --- a/tests/extmod/ure_error.py +++ b/tests/extmod/ure_error.py @@ -9,17 +9,19 @@ 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 4e39468c5ba0a..41425dd62347f 100644 --- a/tests/extmod/ure_group.py +++ b/tests/extmod/ure_group.py @@ -9,8 +9,9 @@ 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 4fac896d7fdbb..7da072a920658 100644 --- a/tests/extmod/ure_groups.py +++ b/tests/extmod/ure_groups.py @@ -13,21 +13,21 @@ 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_limit.py b/tests/extmod/ure_limit.py new file mode 100644 index 0000000000000..99c6a818e8577 --- /dev/null +++ b/tests/extmod/ure_limit.py @@ -0,0 +1,34 @@ +# Test overflow in ure.compile output code. + +try: + import ure as re +except ImportError: + print("SKIP") + raise SystemExit + + +def test_re(r): + try: + re.compile(r) + except: + print("Error") + + +# too many chars in [] +test_re("[" + "a" * 256 + "]") + +# too many groups +test_re("(a)" * 256) + +# jump too big for ? +test_re("(" + "a" * 62 + ")?") + +# jump too big for * +test_re("(" + "a" * 60 + ".)*") +test_re("(" + "a" * 60 + "..)*") + +# jump too big for + +test_re("(" + "a" * 62 + ")+") + +# jump too big for | +test_re("b" * 63 + "|a") diff --git a/tests/extmod/ure_limit.py.exp b/tests/extmod/ure_limit.py.exp new file mode 100644 index 0000000000000..8353be536c300 --- /dev/null +++ b/tests/extmod/ure_limit.py.exp @@ -0,0 +1,7 @@ +Error +Error +Error +Error +Error +Error +Error diff --git a/tests/extmod/ure_namedclass.py b/tests/extmod/ure_namedclass.py index 215d09613f4b0..00d58ad98adb0 100644 --- a/tests/extmod/ure_namedclass.py +++ b/tests/extmod/ure_namedclass.py @@ -9,8 +9,9 @@ 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 50f44399ce714..03a3fef9f3d1a 100644 --- a/tests/extmod/ure_span.py +++ b/tests/extmod/ure_span.py @@ -13,12 +13,12 @@ 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 da6e9652d03e2..51bad791efb88 100644 --- a/tests/extmod/ure_split_notimpl.py +++ b/tests/extmod/ure_split_notimpl.py @@ -4,8 +4,8 @@ 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 f5a19af8db1b7..6bb332077dd29 100644 --- a/tests/extmod/ure_sub.py +++ b/tests/extmod/ure_sub.py @@ -4,58 +4,59 @@ 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 4795b3196f466..d6312bfc2cbc2 100644 --- a/tests/extmod/ure_sub_unmatched.py +++ b/tests/extmod/ure_sub_unmatched.py @@ -6,14 +6,14 @@ 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/uselect_poll_basic.py b/tests/extmod/uselect_poll_basic.py new file mode 100644 index 0000000000000..ab750078d3e61 --- /dev/null +++ b/tests/extmod/uselect_poll_basic.py @@ -0,0 +1,36 @@ +try: + import usocket as socket, uselect as select, uerrno as errno +except ImportError: + try: + import socket, select, errno + + select.poll # Raises AttributeError for CPython implementations without poll() + except (ImportError, AttributeError): + print("SKIP") + raise SystemExit + + +poller = select.poll() + +s = socket.socket() + +poller.register(s) +# https://docs.python.org/3/library/select.html#select.poll.register +# "Registering a file descriptor that’s already registered is not an error, +# and has the same effect as registering the descriptor exactly once." +poller.register(s) + +# 2 args are mandatory unlike register() +try: + poller.modify(s) +except TypeError: + print("modify:TypeError") + +poller.modify(s, select.POLLIN) + +poller.unregister(s) + +try: + poller.modify(s, select.POLLIN) +except OSError as e: + assert e.args[0] == errno.ENOENT diff --git a/tests/extmod/ussl_basic.py b/tests/extmod/ussl_basic.py index e8710ed51ab4b..c8bdc81a48bf0 100644 --- a/tests/extmod/ussl_basic.py +++ b/tests/extmod/ussl_basic.py @@ -11,7 +11,7 @@ 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 @@ 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 @@ 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 dc7f3b6600404..234d7a31dd4a5 100644 --- a/tests/extmod/utimeq1.py +++ b/tests/extmod/utimeq1.py @@ -13,12 +13,17 @@ 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 @@ def dprint(*v): 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 @@ def add(h, v): 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 112a82597638a..6a0aae8bcdf63 100644 --- a/tests/extmod/uzlib_decompio.py +++ b/tests/extmod/uzlib_decompio.py @@ -7,7 +7,7 @@ # 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 @@ # 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 02087f76392a7..1bc8ba885ba54 100644 --- a/tests/extmod/uzlib_decompio_gz.py +++ b/tests/extmod/uzlib_decompio_gz.py @@ -7,7 +7,9 @@ # 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(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 @@ 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 dd6e4876fa345..8d4a9640b471f 100644 --- a/tests/extmod/uzlib_decompress.py +++ b/tests/extmod/uzlib_decompress.py @@ -9,15 +9,24 @@ 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 @@ # 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 fbcc92bade711..c8e203b3df882 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 @@ 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 @@ def open(self, file, mode): 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 4635ca84b53ad..85a7158703432 100644 --- a/tests/extmod/vfs_fat_fileio1.py +++ b/tests/extmod/vfs_fat_fileio1.py @@ -20,19 +20,19 @@ def __init__(self, blocks): 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 @@ def ioctl(self, op, arg): 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 @@ def ioctl(self, op, arg): 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 @@ def ioctl(self, op, arg): 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 @@ def ioctl(self, op, arg): 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 @@ def ioctl(self, op, arg): # 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 ab9623ddf8cd6..2b8c8155c70c6 100644 --- a/tests/extmod/vfs_fat_fileio2.py +++ b/tests/extmod/vfs_fat_fileio2.py @@ -20,19 +20,19 @@ def __init__(self, blocks): 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 @@ def ioctl(self, op, arg): 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 @@ def ioctl(self, op, arg): 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 8ddaf49fc255c..d5ecd50467a6c 100644 --- a/tests/extmod/vfs_fat_more.py +++ b/tests/extmod/vfs_fat_more.py @@ -1,4 +1,3 @@ -import uerrno try: import uos except ImportError: @@ -20,19 +19,19 @@ def __init__(self, blocks): 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 +47,76 @@ def ioctl(self, op, arg): # 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 b671f3db2b59e..e447ff4eb3129 100644 --- a/tests/extmod/vfs_fat_oldproto.py +++ b/tests/extmod/vfs_fat_oldproto.py @@ -11,6 +11,7 @@ print("SKIP") raise SystemExit + class RAMFS_OLD: SEC_SIZE = 512 @@ -19,13 +20,13 @@ def __init__(self, blocks): 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 30a94ec4e114d..c883d522c0d65 100644 --- a/tests/extmod/vfs_fat_ramdisk.py +++ b/tests/extmod/vfs_fat_ramdisk.py @@ -20,19 +20,19 @@ def __init__(self, blocks): 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 @@ def ioctl(self, op, arg): 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 @@ def ioctl(self, op, arg): 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 @@ def ioctl(self, op, arg): 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 e913f9748c1c7..06e546b081a97 100644 --- a/tests/extmod/vfs_userfs.py +++ b/tests/extmod/vfs_userfs.py @@ -1,11 +1,14 @@ # test VFS functionality with a user-defined filesystem # also tests parts of uio.IOBase implementation -import sys, uio +import sys try: + import uio + uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -16,8 +19,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 +30,49 @@ def readinto(self, buf): 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 9a80503a0373f..8c5cf58257305 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 @@ def ws_write(msg, sz): # 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 d60f93956852d..c82a41a24b1c0 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 dcda53eae24bb..82647ee314d9a 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 af93f5976321c..d6d2a99d2429d 100644 --- a/tests/feature_check/float.py +++ b/tests/feature_check/float.py @@ -5,9 +5,9 @@ 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 668748bc5742f..68eb91b44e39e 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 938675835bbcf..6b5c996312d9c 100644 --- a/tests/float/array_construct.py +++ b/tests/float/array_construct.py @@ -6,5 +6,5 @@ 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_abs.py b/tests/float/builtin_float_abs.py new file mode 100644 index 0000000000000..f7ce9e156fe96 --- /dev/null +++ b/tests/float/builtin_float_abs.py @@ -0,0 +1,13 @@ +# test builtin abs function with float args + +for val in ( + "1.0", + "-1.0", + "0.0", + "-0.0", + "nan", + "-nan", + "inf", + "-inf", +): + print(val, abs(float(val))) diff --git a/tests/float/builtin_float_hash.py b/tests/float/builtin_float_hash.py index 7a7e374010104..1388bb0e832f7 100644 --- a/tests/float/builtin_float_hash.py +++ b/tests/float/builtin_float_hash.py @@ -2,24 +2,24 @@ # 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', - ): + "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', - ): + "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 2de1b481763f3..98998bdc7c3fe 100644 --- a/tests/float/builtin_float_pow.py +++ b/tests/float/builtin_float_pow.py @@ -6,6 +6,6 @@ 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 63cb39aa3576b..1153b8a2bfd46 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 @@ 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 2083e3ea3af46..c8a338eefdfa3 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 e960d624ec8ca..f84fa7be58c36 100644 --- a/tests/float/bytearray_construct.py +++ b/tests/float/bytearray_construct.py @@ -6,4 +6,4 @@ 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 0e4482e436698..c24263758eec4 100644 --- a/tests/float/bytes_construct.py +++ b/tests/float/bytes_construct.py @@ -6,4 +6,4 @@ 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 ae5921c304cb8..56229182825c5 100644 --- a/tests/float/cmath_fun.py +++ b/tests/float/cmath_fun.py @@ -11,29 +11,35 @@ 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: @@ -50,6 +56,6 @@ else: # some test (eg cmath.sqrt(-0.5)) disagree with CPython with tiny real part real = ret.real - if abs(real) < 1e15: - real = 0. + if abs(real) < 1e-6: + 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 471fda8c0dc19..33b94d04db43d 100644 --- a/tests/float/cmath_fun_special.py +++ b/tests/float/cmath_fun_special.py @@ -2,26 +2,27 @@ 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), + ("log10", log10, test_values_non_zero), ] for f_name, f, test_vals in functions: diff --git a/tests/float/complex1.py b/tests/float/complex1.py index 479b4b3485b26..e6338551c5ff0 100644 --- a/tests/float/complex1.py +++ b/tests/float/complex1.py @@ -27,18 +27,23 @@ 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(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 @@ 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 ed2390bbaf24c..864036b9914ea 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 54807e5ac9c27..e51e96fd996d0 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) # comparison of nan is special -nan = float('nan') +nan = float("nan") print(nan == 1.2) print(nan == nan) @@ -106,7 +106,7 @@ 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 de2137d66ca64..24d30fe69198d 100644 --- a/tests/float/float2int_doubleprec_intbig.py +++ b/tests/float/float2int_doubleprec_intbig.py @@ -6,6 +6,7 @@ import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -31,32 +32,33 @@ # 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 fbb94a4ccc052..da3980040133c 100644 --- a/tests/float/float2int_fp30_intbig.py +++ b/tests/float/float2int_fp30_intbig.py @@ -6,6 +6,7 @@ import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -30,30 +31,31 @@ 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 3596d2f73da53..30522d44ffff1 100644 --- a/tests/float/float2int_intbig.py +++ b/tests/float/float2int_intbig.py @@ -32,30 +32,31 @@ # 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 8c8edcff7c86b..04212c44f4ff2 100644 --- a/tests/float/float_array.py +++ b/tests/float/float_array.py @@ -4,17 +4,19 @@ 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')) +test(array("f")) +test(array("d")) -print('{:.4f}'.format(array('f', b'\xcc\xcc\xcc=')[0])) +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 105923ac733af..c177aa7e81d52 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 8e7cd435a55e6..ec83ce2d195bb 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 a9450fa2c4d94..ef5a6ad2e82b3 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 @@ def test(x, y): 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 d43535cf2ff4f..4c8a217567abf 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 4b026de1c8103..de27c33e7be57 100644 --- a/tests/float/float_parse.py +++ b/tests/float/float_parse.py @@ -1,32 +1,36 @@ # 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")) + +# check small decimals are as close to their true value as possible +for n in range(1, 10): + print(float("0.%u" % n) == n / 10) diff --git a/tests/float/float_parse_doubleprec.py b/tests/float/float_parse_doubleprec.py index dcc0dd5921544..81fcadcee88b4 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 dd7a418ad5fd4..18893af0e0aa1 100644 --- a/tests/float/float_struct.py +++ b/tests/float/float_struct.py @@ -8,10 +8,10 @@ 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 @@ def test(fmt, *args): 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 269023e7ffb62..7a36f4d2f95dc 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 77b2a528852c2..5f0b213daa342 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 @@ def test(fmt, *args): 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 @@ def test(fmt, *args): 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 aea534247cc20..09446153810db 100644 --- a/tests/float/string_format_modulo.py +++ b/tests/float/string_format_modulo.py @@ -7,9 +7,9 @@ # 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("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 f6b1ae537d5e4..b22021c5d004a 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 9992ba65d9d3d..8110bc7f62e2f 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 5d26f25751d49..f9d9c43cdf42d 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 df415f0031db0..4c8d2e5c8212d 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 088f631fcd3c4..5258da89168e4 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 02f1531467f10..b7567cf02d96c 100644 --- a/tests/import/gen_context.py +++ b/tests/import/gen_context.py @@ -2,8 +2,10 @@ 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 16b2d4d30f61c..9d7d72ff77822 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 be74eca094b52..8c9d15a71f4bc 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 def6aeb6aa383..8fb4905250169 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 2e9d41f71dbdf..2fadd8a52ba64 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 cb9a88a706ec6..90ec4e41e77aa 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_long_dyn.py b/tests/import/import_long_dyn.py new file mode 100644 index 0000000000000..709e019f3199f --- /dev/null +++ b/tests/import/import_long_dyn.py @@ -0,0 +1 @@ +from import_long_dyn2 import * diff --git a/tests/import/import_long_dyn2.py b/tests/import/import_long_dyn2.py new file mode 100644 index 0000000000000..c3cb1f246933f --- /dev/null +++ b/tests/import/import_long_dyn2.py @@ -0,0 +1 @@ +globals()["long_long_very_long_long_name"] = 1 diff --git a/tests/import/import_pkg1.py b/tests/import/import_pkg1.py index fe6e4473e3388..5c1b2ef4c75ba 100644 --- a/tests/import/import_pkg1.py +++ b/tests/import/import_pkg1.py @@ -12,5 +12,6 @@ # 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 0ee885b220860..ec4697906205d 100644 --- a/tests/import/import_pkg3.py +++ b/tests/import/import_pkg3.py @@ -3,4 +3,5 @@ print(mod.foo()) import pkg.mod + print(mod is pkg.mod) diff --git a/tests/import/module_getattr.py b/tests/import/module_getattr.py new file mode 100644 index 0000000000000..df7a6218156c5 --- /dev/null +++ b/tests/import/module_getattr.py @@ -0,0 +1,24 @@ +# test __getattr__ on module + +# ensure that does_not_exist doesn't exist to start with +this = __import__(__name__) +try: + this.does_not_exist + assert False +except AttributeError: + pass + +# define __getattr__ +def __getattr__(attr): + if attr == "does_not_exist": + return False + raise AttributeError + + +# do feature test (will also test functionality if the feature exists) +if not hasattr(this, "does_not_exist"): + print("SKIP") + raise SystemExit + +# check that __getattr__ works as expected +print(this.does_not_exist) diff --git a/tests/pyb/switch.py.exp b/tests/import/module_getattr.py.exp similarity index 100% rename from tests/pyb/switch.py.exp rename to tests/import/module_getattr.py.exp diff --git a/tests/import/mpy_invalid.py b/tests/import/mpy_invalid.py index b9dd99a4408f5..188fb1612789e 100644 --- a/tests/import/mpy_invalid.py +++ b/tests/import/mpy_invalid.py @@ -5,6 +5,7 @@ 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 @@ def readinto(self, buf): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): return 0 @@ -31,37 +35,41 @@ def ioctl(self, req, arg): 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 67f43bad5217f..37721faaf3191 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 923531c1b91f5..5215da2ec49d8 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 6b8b84d0eee22..80817917daedb 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 e8d863c6cdd42..0abc82404dc5d 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 6b574114d1863..0a5eb15052f25 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 039a5d174995b..657a6fb523666 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 c73e2081f0c22..0aa916d2082d2 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 @@ 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 b98f02ce6e01d..3d3d53a16273e 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 03a9db15b5702..7c97df28b342e 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 047d9ed4200f1..3b03f15103b88 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 540fa6591fb9d..08967d48c7484 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 8cf92b301f76d..d1c8a98235ca6 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 d08c0ed6b3e03..43585dddccea6 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 299a25093c7b3..8412dd2c72b6e 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 b97d566eb54c1..c2784638460ae 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 2bdfccf0e0cef..f69c89cdc6c6b 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 d4fa1f2410cff..47fd99a347ab5 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 4c480671f9fef..c65f8a798b96d 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 043a28e22985e..930ddd053cf97 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 7b7d52e2380a8..519fde4fcc3b2 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 57bfcc7f9ad86..640258e7c878f 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 c9005434ba477..74e729dfa2534 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 f1918696eeaeb..95068795df140 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 0df2187347068..ba4c21b3f2152 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 2d3b0e396f41f..053ae29a4d9cd 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 07e71c7384927..f465b25afda75 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 a13f2cad21802..53254da11906b 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/builtin_print_file.py b/tests/io/builtin_print_file.py index d9b8e2a960adb..822356a6cc305 100644 --- a/tests/io/builtin_print_file.py +++ b/tests/io/builtin_print_file.py @@ -5,13 +5,13 @@ 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 af4176b64e9f2..2a46c9c63e360 100644 --- a/tests/io/file1.py +++ b/tests/io/file1.py @@ -4,43 +4,43 @@ 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 cbefc6e040997..1f3702a217e60 100644 --- a/tests/io/file_readinto.py +++ b/tests/io/file_readinto.py @@ -7,8 +7,8 @@ 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 25e76597b150c..86d010eaf657a 100644 --- a/tests/io/file_readline.py +++ b/tests/io/file_readline.py @@ -6,9 +6,9 @@ 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 10fb1fd06f096..2fe57692c63bc 100644 --- a/tests/io/file_seek.py +++ b/tests/io/file_seek.py @@ -25,10 +25,10 @@ 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 ee1e702422b3a..899c0f9287be4 100644 --- a/tests/io/file_with.py +++ b/tests/io/file_with.py @@ -15,7 +15,7 @@ # 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/open_append.py b/tests/io/open_append.py index a696823bc5604..49cdd094b3d56 100644 --- a/tests/io/open_append.py +++ b/tests/io/open_append.py @@ -3,13 +3,13 @@ except ImportError: import os -if not hasattr(os, "unlink"): +if not hasattr(os, "remove"): print("SKIP") raise SystemExit # cleanup in case testfile exists try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass @@ -32,6 +32,6 @@ # cleanup try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass diff --git a/tests/io/open_plus.py b/tests/io/open_plus.py index bba96fa2f9895..3cb2330eed4a4 100644 --- a/tests/io/open_plus.py +++ b/tests/io/open_plus.py @@ -3,13 +3,13 @@ except ImportError: import os -if not hasattr(os, "unlink"): +if not hasattr(os, "remove"): print("SKIP") raise SystemExit # cleanup in case testfile exists try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass @@ -42,6 +42,6 @@ # cleanup try: - os.unlink("testfile") + os.remove("testfile") except OSError: pass diff --git a/tests/io/resource_stream.py b/tests/io/resource_stream.py index 37d985bf16614..5656205b692d6 100644 --- a/tests/io/resource_stream.py +++ b/tests/io/resource_stream.py @@ -4,7 +4,7 @@ try: uio.resource_stream except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit buf = uio.resource_stream("data", "file2") diff --git a/tests/jni/list.py b/tests/jni/list.py index d58181d0bad0e..7630a48e89928 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 aa67615ec8a83..8fbdb39d3929f 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 86c4b9e112163..c34d7011f7987 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 660a095f2c327..1faf22be9a430 100644 --- a/tests/micropython/const.py +++ b/tests/micropython/const.py @@ -7,9 +7,11 @@ print(X, Y + 1) + def f(): print(X, Y + 1) + f() _X = const(12) @@ -17,9 +19,11 @@ def f(): 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 60085a1e04451..ed4720122ed39 100644 --- a/tests/micropython/const2.py +++ b/tests/micropython/const2.py @@ -8,27 +8,37 @@ # 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 6d3d135b56ebb..311cfb4d5e09b 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 e74902652627e..27990c8c20303 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 bf688968a0a23..2e7cf177760e7 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 c7da3119f4a06..94772ac1e5fef 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 4a9fa18bc1751..bca4d2d9fbaca 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 @@ except AttributeError: pass + def f(): micropython.heap_lock() try: @@ -31,4 +33,5 @@ def f(): else: print(l) + f() diff --git a/tests/micropython/emg_exc.py.exp b/tests/micropython/emg_exc.py.exp index fd2cfb2722518..0d4b80ce2bc59 100644 --- a/tests/micropython/emg_exc.py.exp +++ b/tests/micropython/emg_exc.py.exp @@ -1,4 +1,4 @@ Traceback (most recent call last): -, line 20, in f +, line 22, in f ValueError: 1 diff --git a/tests/micropython/extreme_exc.py b/tests/micropython/extreme_exc.py index b9db9640681b4..dae5b151860fc 100644 --- a/tests/micropython/extreme_exc.py +++ b/tests/micropython/extreme_exc.py @@ -5,8 +5,13 @@ # 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 @@ def stackless(): pass 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 f(): except MemoryError: break try: - f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1) + f( + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 + ) except Exception as er: e = er lst[0] = None @@ -57,6 +134,7 @@ def f(): # should use emergency exception and be unable to resize traceback array def g(): g() + micropython.heap_lock() try: g() @@ -67,13 +145,15 @@ def g(): # 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 h(e): micropython.heap_unlock() print(repr(e)) + main() diff --git a/tests/micropython/heap_lock.py b/tests/micropython/heap_lock.py index ca3f5806a84eb..8558935374f45 100644 --- a/tests/micropython/heap_lock.py +++ b/tests/micropython/heap_lock.py @@ -11,13 +11,13 @@ 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 f74bb92c85533..99f157105daa9 100644 --- a/tests/micropython/heapalloc.py +++ b/tests/micropython/heapalloc.py @@ -5,18 +5,26 @@ # 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_bytesio.py b/tests/micropython/heapalloc_bytesio.py deleted file mode 100644 index 4aae2abf063e8..0000000000000 --- a/tests/micropython/heapalloc_bytesio.py +++ /dev/null @@ -1,18 +0,0 @@ -try: - import uio -except ImportError: - print("SKIP") - raise SystemExit - -import micropython - -data = b"1234" * 16 -buf = uio.BytesIO(64) - -micropython.heap_lock() - -buf.write(data) - -micropython.heap_unlock() - -print(buf.getvalue()) diff --git a/tests/micropython/heapalloc_bytesio.py.exp b/tests/micropython/heapalloc_bytesio.py.exp deleted file mode 100644 index 675761c2bb41e..0000000000000 --- a/tests/micropython/heapalloc_bytesio.py.exp +++ /dev/null @@ -1 +0,0 @@ -b'1234123412341234123412341234123412341234123412341234123412341234' diff --git a/tests/micropython/heapalloc_bytesio2.py b/tests/micropython/heapalloc_bytesio2.py index cd76f580775c7..3b9f141270d5a 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 fb63a84bf367a..99810e0075064 100644 --- a/tests/micropython/heapalloc_exc_raise.py +++ b/tests/micropython/heapalloc_exc_raise.py @@ -4,6 +4,7 @@ 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 3cc497b73a7a1..14d8826bf06ce 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 163e1721115dc..f80a099e94164 100644 --- a/tests/micropython/heapalloc_iter.py +++ b/tests/micropython/heapalloc_iter.py @@ -9,7 +9,8 @@ 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 @@ def 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 @@ def gen_func(): 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 @@ def gen_func(): 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 a8c23393e487d..51afae3d83d06 100644 --- a/tests/micropython/heapalloc_super.py +++ b/tests/micropython/heapalloc_super.py @@ -4,21 +4,30 @@ # 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 813dea4b2187c..eabd09388b90b 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 @@ 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/heapalloc_traceback.py.exp b/tests/micropython/heapalloc_traceback.py.exp index facd0af1379bc..71929db93d5c1 100644 --- a/tests/micropython/heapalloc_traceback.py.exp +++ b/tests/micropython/heapalloc_traceback.py.exp @@ -1,5 +1,5 @@ StopIteration Traceback (most recent call last): - File , line 23, in test + File , line 25, in test StopIteration: diff --git a/tests/micropython/kbd_intr.py b/tests/micropython/kbd_intr.py index 879c9a229f222..81977aaa52f6f 100644 --- a/tests/micropython/kbd_intr.py +++ b/tests/micropython/kbd_intr.py @@ -5,7 +5,7 @@ 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 698bbbd21cacd..9df341fbb8334 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 78e4d24736daf..dee3a4ce2f225 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 6c0592e52de47..07014e90dac2d 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.py b/tests/micropython/native_const.py new file mode 100644 index 0000000000000..b48499550e91b --- /dev/null +++ b/tests/micropython/native_const.py @@ -0,0 +1,21 @@ +# test loading constants in native functions + + +@micropython.native +def f(): + return b"bytes" + + +print(f()) + + +@micropython.native +def f(): + @micropython.native + def g(): + return 123 + + return g + + +print(f()()) diff --git a/tests/micropython/native_const.py.exp b/tests/micropython/native_const.py.exp new file mode 100644 index 0000000000000..9002a0c2e5dd6 --- /dev/null +++ b/tests/micropython/native_const.py.exp @@ -0,0 +1,2 @@ +b'bytes' +123 diff --git a/tests/micropython/native_const_intbig.py b/tests/micropython/native_const_intbig.py index 611b39d8fe8c0..69bc1d2163d1e 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 0cd521de6c464..7c5415375e05b 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 @@ def native_test(x): @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/native_try.py b/tests/micropython/native_try.py new file mode 100644 index 0000000000000..492b59085c778 --- /dev/null +++ b/tests/micropython/native_try.py @@ -0,0 +1,45 @@ +# test native try handling + +# basic try-finally +@micropython.native +def f(): + try: + fail + finally: + print("finally") + + +try: + f() +except NameError: + print("NameError") + +# nested try-except with try-finally +@micropython.native +def f(): + try: + try: + fail + finally: + print("finally") + except NameError: + print("NameError") + + +f() + +# check that locals written to in try blocks keep their values +@micropython.native +def f(): + a = 100 + try: + print(a) + a = 200 + fail + except NameError: + print(a) + a = 300 + print(a) + + +f() diff --git a/tests/micropython/native_try.py.exp b/tests/micropython/native_try.py.exp new file mode 100644 index 0000000000000..96596ce5f5a4f --- /dev/null +++ b/tests/micropython/native_try.py.exp @@ -0,0 +1,7 @@ +finally +NameError +finally +NameError +100 +200 +300 diff --git a/tests/micropython/native_try_deep.py b/tests/micropython/native_try_deep.py new file mode 100644 index 0000000000000..3d31248df0fe6 --- /dev/null +++ b/tests/micropython/native_try_deep.py @@ -0,0 +1,36 @@ +# test native try handling + +# deeply nested try (9 deep) +@micropython.native +def f(): + try: + try: + try: + try: + try: + try: + try: + try: + try: + raise ValueError + finally: + print(8) + finally: + print(7) + finally: + print(6) + finally: + print(5) + finally: + print(4) + finally: + print(3) + finally: + print(2) + finally: + print(1) + except ValueError: + print("ValueError") + + +f() diff --git a/tests/micropython/native_try_deep.py.exp b/tests/micropython/native_try_deep.py.exp new file mode 100644 index 0000000000000..84c6beae316b5 --- /dev/null +++ b/tests/micropython/native_try_deep.py.exp @@ -0,0 +1,9 @@ +8 +7 +6 +5 +4 +3 +2 +1 +ValueError diff --git a/tests/micropython/native_with.py b/tests/micropython/native_with.py new file mode 100644 index 0000000000000..4e20b23856791 --- /dev/null +++ b/tests/micropython/native_with.py @@ -0,0 +1,36 @@ +# test with handling within a native function + + +class C: + def __init__(self): + print("__init__") + + def __enter__(self): + print("__enter__") + + def __exit__(self, a, b, c): + print("__exit__", a, b, c) + + +# basic with +@micropython.native +def f(): + with C(): + print(1) + + +f() + +# nested with and try-except +@micropython.native +def f(): + try: + with C(): + print(1) + fail + print(2) + except NameError: + print("NameError") + + +f() diff --git a/tests/micropython/native_with.py.exp b/tests/micropython/native_with.py.exp new file mode 100644 index 0000000000000..6eef7822fbaf8 --- /dev/null +++ b/tests/micropython/native_with.py.exp @@ -0,0 +1,9 @@ +__init__ +__enter__ +1 +__exit__ None None None +__init__ +__enter__ +1 +__exit__ name 'fail' is not defined None +NameError diff --git a/tests/micropython/opt_level.py b/tests/micropython/opt_level.py index 5a10047f04d4f..3213dc003d630 100644 --- a/tests/micropython/opt_level.py +++ b/tests/micropython/opt_level.py @@ -8,12 +8,12 @@ # 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 74f90cb2de400..6a91459ea3d54 100644 --- a/tests/micropython/schedule.py +++ b/tests/micropython/schedule.py @@ -5,16 +5,18 @@ 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 @@ def callback(arg): # 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 @@ def callback_outer(arg): # 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 bc714755a1a49..266885d9d1897 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 cd953ce07d02d..a696b06628323 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: +def get_addr(x: ptr) -> ptr: return x + @micropython.viper -def memset(dest:ptr8, c:int, n:int): +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 2aebe1b048b6b..8e3225331a429 100644 --- a/tests/micropython/viper_args.py +++ b/tests/micropython/viper_args.py @@ -1,36 +1,67 @@ # 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): +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 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 + +@micropython.viper +def f5(x1: int, x2: int, x3: int, x4: int, x5: int): + print(x1, x2, x3, x4, x5) + + +f5(1, 2, 3, 4, 5) + + +@micropython.viper +def f6(x1: int, x2: int, x3: int, x4: int, x5: int, x6: int): + print(x1, x2, x3, x4, x5, x6) + + +f6(1, 2, 3, 4, 5, 6) # test compiling *x, **x, * args (currently unsupported at runtime) @micropython.viper def f(*x, **y): pass + + @micropython.viper def f(*): pass diff --git a/tests/micropython/viper_args.py.exp b/tests/micropython/viper_args.py.exp index 0ca0f4e906da1..6d64c584a5a29 100644 --- a/tests/micropython/viper_args.py.exp +++ b/tests/micropython/viper_args.py.exp @@ -3,3 +3,5 @@ 1 2 1 2 3 1 2 3 4 +1 2 3 4 5 +1 2 3 4 5 6 diff --git a/tests/micropython/viper_binop_arith.py b/tests/micropython/viper_binop_arith.py index 4d711f1a9ff46..2691404b7b8b7 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 @@ def mul(x:int, y:int): 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): +def and_(x: int, y: int): print(x & y, y & x) + + and_(1, 0) and_(1, 3) -and_(0xf0, 0x3f) +and_(0xF0, 0x3F) and_(-42, 6) + @micropython.viper -def or_(x:int, y:int): +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 dcf91ed89db2f..a4c0809c85523 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 c7c0408959514..daab8fcfb51e9 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 822424982a0ae..4b74b527d3d00 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: +def div(x: int, y: int) -> int: return x // y + @micropython.viper -def mod(x:int, y:int) -> int: +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 8065db291b19b..997c397d4c5e0 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 a168afce959c8..d5ebf837bdde6 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,16 @@ def g(): y = 1 if y: print("y", y) + + g() + +# using an int as a conditional that has the lower 16-bits clear +@micropython.viper +def h(): + z = 0x10000 + if z: + print("z", z) + + +h() diff --git a/tests/micropython/viper_cond.py.exp b/tests/micropython/viper_cond.py.exp index dff71039349c8..beacd48fe66f2 100644 --- a/tests/micropython/viper_cond.py.exp +++ b/tests/micropython/viper_cond.py.exp @@ -1,3 +1,4 @@ not x False x True y 1 +z 65536 diff --git a/tests/micropython/viper_const.py b/tests/micropython/viper_const.py new file mode 100644 index 0000000000000..230b282f2352e --- /dev/null +++ b/tests/micropython/viper_const.py @@ -0,0 +1,21 @@ +# test loading constants in viper functions + + +@micropython.viper +def f(): + return b"bytes" + + +print(f()) + + +@micropython.viper +def f(): + @micropython.viper + def g() -> int: + return 123 + + return g + + +print(f()()) diff --git a/tests/micropython/viper_const.py.exp b/tests/micropython/viper_const.py.exp new file mode 100644 index 0000000000000..9002a0c2e5dd6 --- /dev/null +++ b/tests/micropython/viper_const.py.exp @@ -0,0 +1,2 @@ +b'bytes' +123 diff --git a/tests/micropython/viper_const_intbig.py b/tests/micropython/viper_const_intbig.py new file mode 100644 index 0000000000000..42574820a3c60 --- /dev/null +++ b/tests/micropython/viper_const_intbig.py @@ -0,0 +1,9 @@ +# check loading constants + + +@micropython.viper +def f(): + return 123456789012345678901234567890 + + +print(f()) diff --git a/tests/micropython/viper_const_intbig.py.exp b/tests/micropython/viper_const_intbig.py.exp new file mode 100644 index 0000000000000..1d52d220f88a0 --- /dev/null +++ b/tests/micropython/viper_const_intbig.py.exp @@ -0,0 +1 @@ +123456789012345678901234567890 diff --git a/tests/micropython/viper_error.py b/tests/micropython/viper_error.py index 8472572854adb..790f3d75c4f0e 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") @@ -13,34 +15,37 @@ def test(code): # unknown type test("@micropython.viper\ndef f(x:unknown_type): pass") -# too many arguments -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_error.py.exp b/tests/micropython/viper_error.py.exp index 3a8cb02994126..da9a0ca93ee34 100644 --- a/tests/micropython/viper_error.py.exp +++ b/tests/micropython/viper_error.py.exp @@ -1,7 +1,6 @@ -SyntaxError('parameter annotation must be an identifier',) -SyntaxError('return annotation must be an identifier',) +SyntaxError('annotation must be an identifier',) +SyntaxError('annotation must be an identifier',) ViperTypeError("unknown type 'unknown_type'",) -ViperTypeError("Viper functions don't currently support more than 4 arguments",) ViperTypeError("local 'x' used before type known",) ViperTypeError("local 'x' has type 'int' but source is 'object'",) ViperTypeError("can't implicitly convert 'ptr' to 'bool'",) diff --git a/tests/micropython/viper_globals.py b/tests/micropython/viper_globals.py new file mode 100644 index 0000000000000..9532dfd895b39 --- /dev/null +++ b/tests/micropython/viper_globals.py @@ -0,0 +1,22 @@ +# test that viper functions capture their globals context + +gl = {} + +exec( + """ +@micropython.viper +def f(): + return x +""", + gl, +) + +# x is not yet in the globals, f should not see it +try: + print(gl["f"]()) +except NameError: + print("NameError") + +# x is in globals, f should now see it +gl["x"] = 123 +print(gl["f"]()) diff --git a/tests/micropython/viper_globals.py.exp b/tests/micropython/viper_globals.py.exp new file mode 100644 index 0000000000000..5731b89c1bf50 --- /dev/null +++ b/tests/micropython/viper_globals.py.exp @@ -0,0 +1,2 @@ +NameError +123 diff --git a/tests/micropython/viper_import.py b/tests/micropython/viper_import.py index 98780074447b9..3df23e17a77c1 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 021e03f2ca336..41389c751d392 100644 --- a/tests/micropython/viper_misc.py +++ b/tests/micropython/viper_misc.py @@ -2,61 +2,79 @@ # 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 @@ def viper_raise(x:int): @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 e036435c7abce..055c08d8e53dc 100644 --- a/tests/micropython/viper_misc_intbig.py +++ b/tests/micropython/viper_misc_intbig.py @@ -4,5 +4,8 @@ @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 0b865eb9e7b81..30c85d0669934 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: +def get1(src: ptr16) -> int: return src[1] + @micropython.viper -def memadd(src:ptr16, n:int) -> int: +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 5a5f25d170f99..3ca5a027c0593 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): +def set1(dest: ptr16, val: int): dest[1] = val + @micropython.viper -def memset(dest:ptr16, val:int, n:int): +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 4d8b3846de585..b0b90bcaf551e 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: +def get1(src: ptr32) -> int: return src[1] + @micropython.viper -def memadd(src:ptr32, n:int) -> int: +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 973086e4ad4dc..ff0c371ab8c0d 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): +def set1(dest: ptr32, val: int): dest[1] = val + @micropython.viper -def memset(dest:ptr32, val:int, n:int): +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 0ccf8a1d76ff4..d871bfb689b35 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: +def get1(src: ptr8) -> int: return src[1] + @micropython.viper -def memadd(src:ptr8, n:int) -> int: +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 5a8622eb103ad..baa9e2c6d4776 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): +def set1(dest: ptr8, val: int): dest[1] = val + @micropython.viper -def memset(dest:ptr8, val:int, n:int): +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 2198ed7313e6d..bcaabd3fb409b 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/micropython/viper_try.py b/tests/micropython/viper_try.py new file mode 100644 index 0000000000000..61335af221c7b --- /dev/null +++ b/tests/micropython/viper_try.py @@ -0,0 +1,45 @@ +# test try handling within a viper function + +# basic try-finally +@micropython.viper +def f(): + try: + fail + finally: + print("finally") + + +try: + f() +except NameError: + print("NameError") + +# nested try-except with try-finally +@micropython.viper +def f(): + try: + try: + fail + finally: + print("finally") + except NameError: + print("NameError") + + +f() + +# check that locals written to in try blocks keep their values +@micropython.viper +def f(): + a = 100 + try: + print(a) + a = 200 + fail + except NameError: + print(a) + a = 300 + print(a) + + +f() diff --git a/tests/micropython/viper_try.py.exp b/tests/micropython/viper_try.py.exp new file mode 100644 index 0000000000000..96596ce5f5a4f --- /dev/null +++ b/tests/micropython/viper_try.py.exp @@ -0,0 +1,7 @@ +finally +NameError +finally +NameError +100 +200 +300 diff --git a/tests/micropython/viper_with.py b/tests/micropython/viper_with.py new file mode 100644 index 0000000000000..d640c8ae0f5de --- /dev/null +++ b/tests/micropython/viper_with.py @@ -0,0 +1,36 @@ +# test with handling within a viper function + + +class C: + def __init__(self): + print("__init__") + + def __enter__(self): + print("__enter__") + + def __exit__(self, a, b, c): + print("__exit__", a, b, c) + + +# basic with +@micropython.viper +def f(): + with C(): + print(1) + + +f() + +# nested with and try-except +@micropython.viper +def f(): + try: + with C(): + print(1) + fail + print(2) + except NameError: + print("NameError") + + +f() diff --git a/tests/micropython/viper_with.py.exp b/tests/micropython/viper_with.py.exp new file mode 100644 index 0000000000000..6eef7822fbaf8 --- /dev/null +++ b/tests/micropython/viper_with.py.exp @@ -0,0 +1,9 @@ +__init__ +__enter__ +1 +__exit__ None None None +__init__ +__enter__ +1 +__exit__ name 'fail' is not defined None +NameError diff --git a/tests/misc/features.py b/tests/misc/features.py index de75cb46d419f..455b44fb1ef42 100644 --- a/tests/misc/features.py +++ b/tests/misc/features.py @@ -1,159 +1,205 @@ +try: + str.count +except AttributeError: + print("SKIP") + raise SystemExit + # 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 9a746a8b05d9e..f745c30e8e736 100644 --- a/tests/misc/non_compliant.py +++ b/tests/misc/non_compliant.py @@ -9,137 +9,147 @@ # 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 7e50d2836cdc7..e1c21f3d713c4 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 f120fe1e18dbc..edb3045878ed5 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 @@ 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 + raise Exception("msg") 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 + raise Exception("fail") + + 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: f.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 5bbf9d48b5413..f3bb4189f7fdf 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 @@ def solveNSteps(self, nSteps): 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 bf9438e462bac..d7e8a2d943b5e 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 56f3288e28e68..941965e178cfb 100644 --- a/tests/net_hosted/accept_nonblock.py +++ b/tests/net_hosted/accept_nonblock.py @@ -6,11 +6,11 @@ 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 44b3b8c7cdbd0..ff989110ae1b6 100644 --- a/tests/net_hosted/accept_timeout.py +++ b/tests/net_hosted/accept_timeout.py @@ -8,15 +8,15 @@ 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 6479978bea67c..3a3eaa2ba01e4 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 ece6aa0da9721..90f9b7138e3f2 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 e265c830d0d92..dee5fcfd8997e 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 bf8071d0878a7..7fdafab99ab08 100644 --- a/tests/net_inet/test_tls_sites.py +++ b/tests/net_inet/test_tls_sites.py @@ -6,6 +6,7 @@ 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 @@ def test_one(site, opts): "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/accel.py b/tests/pyb/accel.py deleted file mode 100644 index e5a1a2ed7a441..0000000000000 --- a/tests/pyb/accel.py +++ /dev/null @@ -1,9 +0,0 @@ -import pyb - -accel = pyb.Accel() -print(accel) -accel.x() -accel.y() -accel.z() -accel.tilt() -accel.filtered_xyz() diff --git a/tests/pyb/accel.py.exp b/tests/pyb/accel.py.exp deleted file mode 100644 index 28070be1771bb..0000000000000 --- a/tests/pyb/accel.py.exp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/pyb/adc.py b/tests/pyb/adc.py deleted file mode 100644 index 0bd9b9d53a5ca..0000000000000 --- a/tests/pyb/adc.py +++ /dev/null @@ -1,62 +0,0 @@ -from pyb import ADC, Timer - -adct = ADC(16) # Temperature 930 -> 20C -print(adct) -adcv = ADC(17) # Voltage 1500 -> 3.3V -print(adcv) - -# read single sample; 2.5V-5V is pass range -val = adcv.read() -assert val > 1000 and val < 2000 - -# timer for read_timed -tim = Timer(5, freq=500) - -# read into bytearray -buf = bytearray(b'\xff' * 50) -adcv.read_timed(buf, tim) -print(len(buf)) -for i in buf: - assert i > 50 and i < 150 - -# read into arrays with different element sizes -import array -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]) -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) -ADC.read_timed_multi((adcv, adct), (arv, art), tim) -for i in arv: - assert i > 60 and i < 125 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 15 and i < 200 - -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 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 50 and i < 2000 - -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 -# Wide range: unsure of accuracy of temp sensor. -for i in art: - assert i > 50 and i < 2000 diff --git a/tests/pyb/adc.py.exp b/tests/pyb/adc.py.exp deleted file mode 100644 index 1aae16fb01771..0000000000000 --- a/tests/pyb/adc.py.exp +++ /dev/null @@ -1,5 +0,0 @@ - - -50 -25 -30 diff --git a/tests/pyb/adcall.py b/tests/pyb/adcall.py deleted file mode 100644 index cfe179a97b212..0000000000000 --- a/tests/pyb/adcall.py +++ /dev/null @@ -1,31 +0,0 @@ -from pyb import Pin, ADCAll - -pins = [Pin.cpu.A0, Pin.cpu.A1, Pin.cpu.A2, Pin.cpu.A3] - -# set pins to IN mode, init ADCAll, then check pins are ANALOG -for p in pins: - p.init(p.IN) -adc = ADCAll(12) -for p in pins: - print(p) - -# set pins to IN mode, init ADCAll with mask, then check some pins are ANALOG -for p in pins: - p.init(p.IN) -adc = ADCAll(12, 0x70003) -for p in pins: - print(p) - -# init all pins to ANALOG -adc = ADCAll(12) -print(adc) - -# read all channels -for c in range(19): - print(type(adc.read_channel(c))) - -# call special reading functions -print(0 < adc.read_core_temp() < 100) -print(0 < adc.read_core_vbat() < 4) -print(0 < adc.read_core_vref() < 2) -print(0 < adc.read_vref() < 4) diff --git a/tests/pyb/adcall.py.exp b/tests/pyb/adcall.py.exp deleted file mode 100644 index 5a85ba770e855..0000000000000 --- a/tests/pyb/adcall.py.exp +++ /dev/null @@ -1,32 +0,0 @@ -Pin(Pin.cpu.A0, mode=Pin.ANALOG) -Pin(Pin.cpu.A1, mode=Pin.ANALOG) -Pin(Pin.cpu.A2, mode=Pin.ANALOG) -Pin(Pin.cpu.A3, mode=Pin.ANALOG) -Pin(Pin.cpu.A0, mode=Pin.ANALOG) -Pin(Pin.cpu.A1, mode=Pin.ANALOG) -Pin(Pin.cpu.A2, mode=Pin.IN) -Pin(Pin.cpu.A3, mode=Pin.IN) - - - - - - - - - - - - - - - - - - - - -True -True -True -True diff --git a/tests/pyb/can.py b/tests/pyb/can.py deleted file mode 100644 index 8a08ea9a65b3c..0000000000000 --- a/tests/pyb/can.py +++ /dev/null @@ -1,309 +0,0 @@ -try: - from pyb import CAN -except ImportError: - print('SKIP') - raise SystemExit - -from array import array -import micropython -import pyb - -# test we can correctly create by id or name -for bus in (-1, 0, 1, 2, 3, "YA", "YB", "YC"): - try: - CAN(bus, CAN.LOOPBACK) - print("CAN", bus) - except ValueError: - print("ValueError", bus) -CAN(1).deinit() - -CAN.initfilterbanks(14) -can = CAN(1) -print(can) - -# Test state when de-init'd -print(can.state() == can.STOPPED) - -can.init(CAN.LOOPBACK) -print(can) -print(can.any(0)) - -# Test state when freshly created -print(can.state() == can.ERROR_ACTIVE) - -# Test that restart can be called -can.restart() - -# Test info returns a sensible value -print(can.info()) - -# Catch all filter -can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) - -can.send('abcd', 123, timeout=5000) -print(can.any(0), can.info()) -print(can.recv(0)) - -can.send('abcd', -1, timeout=5000) -print(can.recv(0)) - -can.send('abcd', 0x7FF + 1, timeout=5000) -print(can.recv(0)) - -# Test too long message -try: - can.send('abcdefghi', 0x7FF, timeout=5000) -except ValueError: - print('passed') -else: - print('failed') - -# Test that recv can work without allocating memory on the heap - -buf = bytearray(10) -l = [0, 0, 0, memoryview(buf)] -l2 = None - -micropython.heap_lock() - -can.send('', 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send('1234', 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send('01234567', 42) -l2 = can.recv(0, l) -assert l is l2 -print(l, len(l[3]), buf) - -can.send('abc', 42) -l2 = can.recv(0, l) -assert l is l2 -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])) - -# Test for non-list passed as second arg to recv -can.send('abc', 1) -try: - can.recv(0, 1) -except TypeError: - print('TypeError') - -# Test for too-short-list passed as second arg to recv -can.send('abc', 1) -try: - can.recv(0, [0, 0, 0]) -except ValueError: - print('ValueError') - -# Test for non-memoryview passed as 4th element to recv -can.send('abc', 1) -try: - can.recv(0, [0, 0, 0, 0]) -except TypeError: - print('TypeError') - -# Test for read-only-memoryview passed as 4th element to recv -can.send('abc', 1) -try: - can.recv(0, [0, 0, 0, memoryview(bytes(8))]) -except ValueError: - print('ValueError') - -# Test for bad-typecode-memoryview passed as 4th element to recv -can.send('abc', 1) -try: - can.recv(0, [0, 0, 0, memoryview(array('i', range(8)))]) -except ValueError: - print('ValueError') - -del can - -# Testing extended IDs -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) -except ValueError: - print('failed') -else: - r = can.recv(0) - if r[0] == 0x7FF+1 and r[3] == b'abcde': - print('passed') - else: - print('failed, wrong data received') - -# Test filters -for n in [0, 8, 16, 24]: - filter_id = 0b00001000 << n - filter_mask = 0b00011100 << n - id_ok = 0b00001010 << n - id_fail = 0b00011010 << n - - can.clearfilter(0) - can.setfilter(0, pyb.CAN.MASK32, 0, (filter_id, filter_mask)) - - 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])) - - can.send("fail", id_fail, timeout=3) - if can.any(0): - msg = can.recv(0) - print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) - -del can - -# Test RxCallbacks -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') - if reason == 0: - print('pending') - if reason == 1: - print('full') - if reason == 2: - print('overflow') - -def cb1(bus, reason): - print('cb1') - if reason == 0: - print('pending') - if reason == 1: - print('full') - if reason == 2: - print('overflow') - -def cb0a(bus, reason): - print('cb0a') - if reason == 0: - print('pending') - if reason == 1: - print('full') - if reason == 2: - print('overflow') - -def cb1a(bus, reason): - print('cb1a') - if reason == 0: - print('pending') - if reason == 1: - print('full') - if reason == 2: - 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.rxcallback(0, cb0a) -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.rxcallback(1, cb1a) -can.send('88888888',8, timeout=5000) - -print(can.recv(0)) -print(can.recv(0)) -print(can.recv(0)) -print(can.recv(1)) -print(can.recv(1)) -print(can.recv(1)) - -can.send('11111111',1, timeout=5000) -can.send('55555555',5, timeout=5000) - -print(can.recv(0)) -print(can.recv(1)) - -del can - -# Testing asynchronous send -can = CAN(1, CAN.LOOPBACK) -can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) - -while can.any(0): - can.recv(0) - -can.send('abcde', 1, timeout=0) -print(can.any(0)) -while not can.any(0): - pass - -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) -except OSError as e: - if str(e) == '16': - print('passed') - else: - print('failed') - -pyb.delay(500) -while can.any(0): - print(can.recv(0)) - -# Testing rtr messages -bus1 = CAN(1, CAN.LOOPBACK) -bus2 = CAN(2, CAN.LOOPBACK, extframe = True) -while bus1.any(0): - bus1.recv(0) -while bus2.any(0): - bus2.recv(0) -bus1.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) -bus1.setfilter(1, CAN.LIST16, 0, (5, 6, 7, 8), rtr=(True, True, True, True)) -bus1.setfilter(2, CAN.MASK16, 0, (64, 64, 32, 32), rtr=(False, True)) -bus2.setfilter(0, CAN.LIST32, 0, (1, 2), rtr=(True, True)) -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) -print(bus1.any(0)) -bus1.send('',5,rtr=True) -print(bus1.recv(0)) -bus1.send('',6,rtr=True) -print(bus1.recv(0)) -bus1.send('',7,rtr=True) -print(bus1.recv(0)) -bus1.send('',16,rtr=True) -print(bus1.any(0)) -bus1.send('',32,rtr=True) -print(bus1.recv(0)) - -bus2.send('',1,rtr=True) -print(bus2.recv(0)) -bus2.send('',2,rtr=True) -print(bus2.recv(0)) -bus2.send('',3,rtr=True) -print(bus2.recv(0)) -bus2.send('',4,rtr=True) -print(bus2.any(0)) diff --git a/tests/pyb/can.py.exp b/tests/pyb/can.py.exp deleted file mode 100644 index 687935e7f45bc..0000000000000 --- a/tests/pyb/can.py.exp +++ /dev/null @@ -1,76 +0,0 @@ -ValueError -1 -ValueError 0 -CAN 1 -CAN 2 -ValueError 3 -CAN YA -CAN YB -ValueError YC -CAN(1) -True -CAN(1, CAN.LOOPBACK, extframe=False, auto_restart=False) -False -True -[0, 0, 0, 0, 0, 0, 0, 0] -True [0, 0, 0, 0, 0, 0, 1, 0] -(123, False, 0, b'abcd') -(2047, False, 0, b'abcd') -(0, False, 0, b'abcd') -passed -[42, False, 0, ] 0 bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') -[42, False, 0, ] 4 bytearray(b'1234\x00\x00\x00\x00\x00\x00') -[42, False, 0, ] 8 bytearray(b'01234567\x00\x00') -[42, False, 0, ] 3 bytearray(b'abc34567\x00\x00') -b'abc' -b'def' -TypeError -ValueError -TypeError -ValueError -ValueError -CAN(1, CAN.LOOPBACK, extframe=True, auto_restart=False) -passed -('0x8', '0x1c', '0xa', b'ok') -('0x800', '0x1c00', '0xa00', b'ok') -('0x80000', '0x1c0000', '0xa0000', b'ok') -('0x8000000', '0x1c000000', '0xa000000', b'ok') -cb0 -pending -cb0 -full -cb0a -overflow -cb1 -pending -cb1 -full -cb1a -overflow -(1, False, 0, b'11111111') -(2, False, 1, b'22222222') -(4, False, 3, b'44444444') -(5, False, 0, b'55555555') -(6, False, 1, b'66666666') -(8, False, 3, b'88888888') -cb0a -pending -cb1a -pending -(1, False, 0, b'11111111') -(5, False, 0, b'55555555') -False -(1, False, 0, b'abcde') -passed -(2, False, 0, b'abcde') -(3, False, 0, b'abcde') -(4, False, 0, b'abcde') -False -(5, True, 4, b'') -(6, True, 5, b'') -(7, True, 6, b'') -False -(32, True, 9, b'') -(1, True, 0, b'') -(2, True, 1, b'') -(3, True, 2, b'') -False diff --git a/tests/pyb/dac.py b/tests/pyb/dac.py deleted file mode 100644 index ca68ec7098c5d..0000000000000 --- a/tests/pyb/dac.py +++ /dev/null @@ -1,18 +0,0 @@ -import pyb - -if not hasattr(pyb, 'DAC'): - print('SKIP') - raise SystemExit - -dac = pyb.DAC(1) -print(dac) -dac.noise(100) -dac.triangle(100) -dac.write(0) -dac.write_timed(bytearray(10), 100, mode=pyb.DAC.NORMAL) -pyb.delay(20) -dac.write(0) - -# test buffering arg -dac = pyb.DAC(1, buffering=True) -dac.write(0) diff --git a/tests/pyb/dac.py.exp b/tests/pyb/dac.py.exp deleted file mode 100644 index 7ee99652a8460..0000000000000 --- a/tests/pyb/dac.py.exp +++ /dev/null @@ -1 +0,0 @@ -DAC(1, bits=8) diff --git a/tests/pyb/extint.py b/tests/pyb/extint.py deleted file mode 100644 index ae98ccd5a0de5..0000000000000 --- a/tests/pyb/extint.py +++ /dev/null @@ -1,17 +0,0 @@ -import pyb - -# test basic functionality -ext = pyb.ExtInt('Y1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l)) -ext.disable() -ext.enable() -print(ext.line()) -ext.swint() - -# test swint while disabled, then again after re-enabled -ext.disable() -ext.swint() -ext.enable() -ext.swint() - -# disable now that the test is finished -ext.disable() diff --git a/tests/pyb/extint.py.exp b/tests/pyb/extint.py.exp deleted file mode 100644 index 1f9da9844a081..0000000000000 --- a/tests/pyb/extint.py.exp +++ /dev/null @@ -1,3 +0,0 @@ -6 -line: 6 -line: 6 diff --git a/tests/pyb/halerror.py.exp b/tests/pyb/halerror.py.exp deleted file mode 100644 index 0f3f26253dc81..0000000000000 --- a/tests/pyb/halerror.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -OSError(5,) -OSError(110,) diff --git a/tests/pyb/i2c_error.py.exp b/tests/pyb/i2c_error.py.exp deleted file mode 100644 index bd403f7f47f8f..0000000000000 --- a/tests/pyb/i2c_error.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -OSError(5,) -OSError(5,) -OSError(5,) -OSError(5,) diff --git a/tests/pyb/irq.py b/tests/pyb/irq.py deleted file mode 100644 index 42d276568ebfa..0000000000000 --- a/tests/pyb/irq.py +++ /dev/null @@ -1,22 +0,0 @@ -import pyb - -def test_irq(): - # test basic disable/enable - i1 = pyb.disable_irq() - print(i1) - pyb.enable_irq() # by default should enable IRQ - - # check that interrupts are enabled by waiting for ticks - pyb.delay(10) - - # check nested disable/enable - i1 = pyb.disable_irq() - i2 = pyb.disable_irq() - print(i1, i2) - pyb.enable_irq(i2) - pyb.enable_irq(i1) - - # check that interrupts are enabled by waiting for ticks - pyb.delay(10) - -test_irq() diff --git a/tests/pyb/irq.py.exp b/tests/pyb/irq.py.exp deleted file mode 100644 index aea065f04548a..0000000000000 --- a/tests/pyb/irq.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -True -True False diff --git a/tests/pyb/led.py b/tests/pyb/led.py deleted file mode 100644 index d2a17ebc9adfc..0000000000000 --- a/tests/pyb/led.py +++ /dev/null @@ -1,40 +0,0 @@ -import pyb -from pyb import LED - -l1 = pyb.LED(1) -l2 = pyb.LED(2) -l3 = pyb.LED(3) -l4 = pyb.LED(4) - -leds = [LED(i) for i in range(1, 5)] -pwm_leds = leds[2:] - -# test printing -for l in leds: - print(l) - -# test on and off -for l in leds: - l.on() - assert l.intensity() == 255 - pyb.delay(100) - l.off() - assert l.intensity() == 0 - pyb.delay(100) - -# test toggle -for l in 2 * leds: - l.toggle() - assert l.intensity() in (0, 255) - pyb.delay(100) - -# test intensity -for l in pwm_leds: - for i in range(256): - l.intensity(i) - assert l.intensity() == i - pyb.delay(1) - for i in range(255, -1, -1): - l.intensity(i) - assert l.intensity() == i - pyb.delay(1) diff --git a/tests/pyb/led.py.exp b/tests/pyb/led.py.exp deleted file mode 100644 index 4e8d856cd94b0..0000000000000 --- a/tests/pyb/led.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -LED(1) -LED(2) -LED(3) -LED(4) diff --git a/tests/pyb/modstm.py b/tests/pyb/modstm.py deleted file mode 100644 index f1e147c0529b0..0000000000000 --- a/tests/pyb/modstm.py +++ /dev/null @@ -1,13 +0,0 @@ -# test stm module - -import stm -import pyb - -# test storing a full 32-bit number -# turn on then off the A15(=yellow) LED -BSRR = 0x18 -stm.mem32[stm.GPIOA + BSRR] = 0x00008000 -pyb.delay(100) -print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000)) -stm.mem32[stm.GPIOA + BSRR] = 0x80000000 -print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000)) diff --git a/tests/pyb/modstm.py.exp b/tests/pyb/modstm.py.exp deleted file mode 100644 index a24c9f86579c6..0000000000000 --- a/tests/pyb/modstm.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -0x8000 -0x0 diff --git a/tests/pyb/modtime.py b/tests/pyb/modtime.py deleted file mode 100644 index d45440a63c7fa..0000000000000 --- a/tests/pyb/modtime.py +++ /dev/null @@ -1,59 +0,0 @@ -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 - for year in range(2000, 2034): - print("Testing %d" % year) - yday = 1 - for month in range(1, 13): - if month == 2 and is_leap(year): - DAYS_PER_MONTH[2] = 29 - else: - DAYS_PER_MONTH[2] = 28 - 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)) - 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)) - return - seconds += 86400 - if yday != tuple[7]: - 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)) - 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) - 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)) diff --git a/tests/pyb/modtime.py.exp b/tests/pyb/modtime.py.exp deleted file mode 100644 index 3e1f6e920c385..0000000000000 --- a/tests/pyb/modtime.py.exp +++ /dev/null @@ -1,46 +0,0 @@ -Testing 2000 -Testing 2001 -Testing 2002 -Testing 2003 -Testing 2004 -Testing 2005 -Testing 2006 -Testing 2007 -Testing 2008 -Testing 2009 -Testing 2010 -Testing 2011 -Testing 2012 -Testing 2013 -Testing 2014 -Testing 2015 -Testing 2016 -Testing 2017 -Testing 2018 -Testing 2019 -Testing 2020 -Testing 2021 -Testing 2022 -Testing 2023 -Testing 2024 -Testing 2025 -Testing 2026 -Testing 2027 -Testing 2028 -Testing 2029 -Testing 2030 -Testing 2031 -Testing 2032 -Testing 2033 -time.localtime( 0 ) returned (2000, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( 1 ) returned (2000, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( 59 ) returned (2000, 1, 1, 0, 0, 59, 5, 1) (pass) -time.localtime( 60 ) returned (2000, 1, 1, 0, 1, 0, 5, 1) (pass) -time.localtime( 3599 ) returned (2000, 1, 1, 0, 59, 59, 5, 1) (pass) -time.localtime( 3600 ) returned (2000, 1, 1, 1, 0, 0, 5, 1) (pass) -time.localtime( -1 ) returned (1999, 12, 31, 23, 59, 59, 4, 365) (pass) -time.localtime( 447549467 ) returned (2014, 3, 7, 23, 17, 47, 4, 66) (pass) -time.localtime( -940984933 ) returned (1970, 3, 7, 23, 17, 47, 5, 66) (pass) -time.localtime( -1072915199 ) returned (1966, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( -1072915200 ) returned (1966, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( -1072915201 ) returned (1965, 12, 31, 23, 59, 59, 4, 365) (pass) diff --git a/tests/pyb/pin.py b/tests/pyb/pin.py deleted file mode 100644 index 9b37883438f33..0000000000000 --- a/tests/pyb/pin.py +++ /dev/null @@ -1,33 +0,0 @@ -from pyb import Pin - -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) -print(p) -print(p.value()) - -p.init(p.IN, p.PULL_DOWN) -p.init(p.IN, pull=p.PULL_DOWN) -p.init(mode=p.IN, pull=p.PULL_DOWN) -print(p) -print(p.value()) - -p.init(p.OUT_PP) -p.low() -print(p.value()) -p.high() -print(p.value()) -p.value(0) -print(p.value()) -p.value(1) -print(p.value()) -p.value(False) -print(p.value()) -p.value(True) -print(p.value()) diff --git a/tests/pyb/pin.py.exp b/tests/pyb/pin.py.exp deleted file mode 100644 index f2f7038fd44b5..0000000000000 --- a/tests/pyb/pin.py.exp +++ /dev/null @@ -1,14 +0,0 @@ -Pin(Pin.cpu.C6, mode=Pin.IN) -C6 -6 -2 -Pin(Pin.cpu.C6, mode=Pin.IN, pull=Pin.PULL_UP) -1 -Pin(Pin.cpu.C6, mode=Pin.IN, pull=Pin.PULL_DOWN) -0 -0 -1 -0 -1 -0 -1 diff --git a/tests/pyb/pyb1.py b/tests/pyb/pyb1.py deleted file mode 100644 index 443722ca85970..0000000000000 --- a/tests/pyb/pyb1.py +++ /dev/null @@ -1,39 +0,0 @@ -# basic tests of pyb module - -import pyb - -# test delay - -pyb.delay(-1) -pyb.delay(0) -pyb.delay(1) - -start = pyb.millis() -pyb.delay(17) -print((pyb.millis() - start) // 5) # should print 3 - -# test udelay - -pyb.udelay(-1) -pyb.udelay(0) -pyb.udelay(1) - -start = pyb.millis() -pyb.udelay(17000) -print((pyb.millis() - start) // 5) # should print 3 - -# other - -pyb.disable_irq() -pyb.enable_irq() - -print(pyb.have_cdc()) - -pyb.sync() - -print(len(pyb.unique_id())) - -pyb.wfi() - -pyb.fault_debug(True) -pyb.fault_debug(False) diff --git a/tests/pyb/pyb1.py.exp b/tests/pyb/pyb1.py.exp deleted file mode 100644 index 5816ea967b3cb..0000000000000 --- a/tests/pyb/pyb1.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -3 -3 -True -12 diff --git a/tests/pyb/pyb_f405.py b/tests/pyb/pyb_f405.py deleted file mode 100644 index 2f161ae099592..0000000000000 --- a/tests/pyb/pyb_f405.py +++ /dev/null @@ -1,10 +0,0 @@ -# test pyb module on F405 MCUs - -import os, pyb - -if not 'STM32F405' in os.uname().machine: - print('SKIP') - raise SystemExit - -print(pyb.freq()) -print(type(pyb.rng())) diff --git a/tests/pyb/pyb_f405.py.exp b/tests/pyb/pyb_f405.py.exp deleted file mode 100644 index a90aa0268659e..0000000000000 --- a/tests/pyb/pyb_f405.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -(168000000, 168000000, 42000000, 84000000) - diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py deleted file mode 100644 index 50de30282376f..0000000000000 --- a/tests/pyb/pyb_f411.py +++ /dev/null @@ -1,9 +0,0 @@ -# test pyb module on F411 MCUs - -import os, pyb - -if not 'STM32F411' in os.uname().machine: - print('SKIP') - raise SystemExit - -print(pyb.freq()) diff --git a/tests/pyb/pyb_f411.py.exp b/tests/pyb/pyb_f411.py.exp deleted file mode 100644 index 79e0a10621737..0000000000000 --- a/tests/pyb/pyb_f411.py.exp +++ /dev/null @@ -1 +0,0 @@ -(96000000, 96000000, 24000000, 48000000) diff --git a/tests/pyb/rtc.py b/tests/pyb/rtc.py deleted file mode 100644 index 844526b4b9683..0000000000000 --- a/tests/pyb/rtc.py +++ /dev/null @@ -1,79 +0,0 @@ -import pyb, stm -from pyb import RTC - -rtc = RTC() -rtc.init() -print(rtc) - -# make sure that 1 second passes correctly -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)) -set_and_print((2000, 12, 31, 1, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 1, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 0, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 1, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 12, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 13, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 0, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 1, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 0, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 1, 0)) -set_and_print((2016, 12, 31, 7, 23, 59, 59, 0)) -set_and_print((2099, 12, 31, 7, 23, 59, 59, 0)) - -# check that calibration works correctly -# 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) -set_and_print_calib(1) -set_and_print_calib(0) -set_and_print_calib(-1) -set_and_print_calib(-123) -set_and_print_calib(-510) -set_and_print_calib(-511) - -# restore existing calibration value -rtc.calibration(cal_tmp) - -# Check register settings for wakeup -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 - except ValueError: - wucksel = -1 - wut = -1 - print((wucksel, wut)) - -set_and_print_wakeup(0) -set_and_print_wakeup(1) -set_and_print_wakeup(4000) -set_and_print_wakeup(4001) -set_and_print_wakeup(8000) -set_and_print_wakeup(8001) -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 diff --git a/tests/pyb/rtc.py.exp b/tests/pyb/rtc.py.exp deleted file mode 100644 index 7d3aaf6af7d41..0000000000000 --- a/tests/pyb/rtc.py.exp +++ /dev/null @@ -1,40 +0,0 @@ - -(2014, 1, 1, 1, 0, 0, 1) -(2000, 1, 1, 1, 0, 0, 0) -(2000, 1, 31, 1, 0, 0, 0) -(2000, 12, 31, 1, 0, 0, 0) -(2016, 12, 31, 1, 0, 0, 0) -(2016, 12, 31, 7, 0, 0, 0) -(2016, 12, 31, 7, 1, 0, 0) -(2016, 12, 31, 7, 12, 0, 0) -(2016, 12, 31, 7, 13, 0, 0) -(2016, 12, 31, 7, 23, 0, 0) -(2016, 12, 31, 7, 23, 1, 0) -(2016, 12, 31, 7, 23, 59, 0) -(2016, 12, 31, 7, 23, 59, 1) -(2016, 12, 31, 7, 23, 59, 59) -(2099, 12, 31, 7, 23, 59, 59) -512 -511 -345 -1 -0 --1 --123 --510 --511 -(3, 0) -(3, 15) -(3, 65535) -(2, 32775) -(2, 65535) -(1, 32771) -(1, 65535) -(0, 32769) -(0, 65535) -(4, 31) -(4, 65535) -(6, 0) -(6, 65534) -(6, 65535) -(-1, -1) diff --git a/tests/pyb/servo.py b/tests/pyb/servo.py deleted file mode 100644 index d15cafe483e01..0000000000000 --- a/tests/pyb/servo.py +++ /dev/null @@ -1,16 +0,0 @@ -from pyb import Servo - -servo = Servo(1) -print(servo) - -servo.angle(0) -servo.angle(10, 100) - -servo.speed(-10) -servo.speed(10, 100) - -servo.pulse_width(1500) -print(servo.pulse_width()) - -servo.calibration(630, 2410, 1490, 2460, 2190) -print(servo.calibration()) diff --git a/tests/pyb/servo.py.exp b/tests/pyb/servo.py.exp deleted file mode 100644 index ac6032ba5fa0a..0000000000000 --- a/tests/pyb/servo.py.exp +++ /dev/null @@ -1,3 +0,0 @@ - -1500 -(630, 2410, 1490, 2460, 2190) diff --git a/tests/pyb/switch.py b/tests/pyb/switch.py deleted file mode 100644 index 7c44adb136cee..0000000000000 --- a/tests/pyb/switch.py +++ /dev/null @@ -1,6 +0,0 @@ -from pyb import Switch - -sw = Switch() -print(sw()) -sw.callback(print) -sw.callback(None) diff --git a/tests/pyb/timer.py b/tests/pyb/timer.py deleted file mode 100644 index 61320690a6ccb..0000000000000 --- a/tests/pyb/timer.py +++ /dev/null @@ -1,13 +0,0 @@ -# check basic functionality of the timer class - -import pyb -from pyb import Timer - -tim = Timer(4) -tim = Timer(4, prescaler=100, period=200) -print(tim.prescaler()) -print(tim.period()) -tim.prescaler(300) -print(tim.prescaler()) -tim.period(400) -print(tim.period()) diff --git a/tests/pyb/timer.py.exp b/tests/pyb/timer.py.exp deleted file mode 100644 index 5c46230303de4..0000000000000 --- a/tests/pyb/timer.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -100 -200 -300 -400 diff --git a/tests/pyb/timer_callback.py b/tests/pyb/timer_callback.py deleted file mode 100644 index 864dd479edc83..0000000000000 --- a/tests/pyb/timer_callback.py +++ /dev/null @@ -1,49 +0,0 @@ -# check callback feature of the timer class - -import pyb -from pyb import Timer - -# callback function that disables the callback when called -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) -print("before cb1") -pyb.delay(15) - -# create a timer with a callback, using deinit to stop -tim = Timer(2, freq=100, callback=cb2) -pyb.delay(5) -print("before cb2") -pyb.delay(15) - -# create a timer, then set the freq, then set the callback -tim = Timer(4) -tim.init(freq=100) -tim.callback(cb1) -pyb.delay(5) -print("before cb1") -pyb.delay(15) - -# test callback with a closure -tim.init(freq=100) -tim.callback(cb3(3)) -pyb.delay(5) -print("before cb4") -pyb.delay(15) diff --git a/tests/pyb/timer_callback.py.exp b/tests/pyb/timer_callback.py.exp deleted file mode 100644 index 9be7cf5b90140..0000000000000 --- a/tests/pyb/timer_callback.py.exp +++ /dev/null @@ -1,8 +0,0 @@ -before cb1 -cb1 -before cb2 -cb2 -before cb1 -cb1 -before cb4 -cb4 3 diff --git a/tests/pyb/uart.py b/tests/pyb/uart.py deleted file mode 100644 index 838dd9cfc6286..0000000000000 --- a/tests/pyb/uart.py +++ /dev/null @@ -1,32 +0,0 @@ -from pyb import UART - -# test we can correctly create by id or name -for bus in (-1, 0, 1, 2, 3, 4, 5, 6, 7, "XA", "XB", "YA", "YB", "Z"): - try: - UART(bus, 9600) - print("UART", bus) - except ValueError: - print("ValueError", bus) - -uart = UART(1) -uart = UART(1, 9600) -uart = UART(1, 9600, bits=8, parity=None, stop=1) -print(uart) - -uart.init(2400) -print(uart) - -print(uart.any()) -print(uart.write('123')) -print(uart.write(b'abcd')) -print(uart.writechar(1)) - -# make sure this method exists -uart.sendbreak() - -# non-blocking mode -uart = UART(1, 9600, timeout=0) -print(uart.write(b'1')) -print(uart.write(b'abcd')) -print(uart.writechar(1)) -print(uart.read(100)) diff --git a/tests/pyb/uart.py.exp b/tests/pyb/uart.py.exp deleted file mode 100644 index b5fe0cd0bd889..0000000000000 --- a/tests/pyb/uart.py.exp +++ /dev/null @@ -1,24 +0,0 @@ -ValueError -1 -ValueError 0 -UART 1 -UART 2 -UART 3 -UART 4 -ValueError 5 -UART 6 -ValueError 7 -UART XA -UART XB -UART YA -UART YB -ValueError Z -UART(1, baudrate=9600, bits=8, parity=None, stop=1, timeout=1000, timeout_char=3, read_buf_len=64) -UART(1, baudrate=2400, bits=8, parity=None, stop=1, timeout=1000, timeout_char=7, read_buf_len=64) -0 -3 -4 -None -1 -4 -None -None diff --git a/tests/pybnative/for.py b/tests/pybnative/for.py index 309c6c14fd075..50177a9ba4854 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 3ea7221ea706a..0f397dd3772a9 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 b/tests/run-tests index e28600361bcc0..e00d6930f0a7c 100755 --- a/tests/run-tests +++ b/tests/run-tests @@ -149,13 +149,15 @@ def run_micropython(pyb, args, test_file, is_special=False): else: # run on pyboard - import pyboard pyb.enter_raw_repl() try: output_mupy = pyb.execfile(test_file) - except pyboard.PyboardError: + except pyboard.PyboardError as e: had_crash = True - output_mupy = b'CRASH' + if not is_special and e.args[0] == 'exception': + output_mupy = e.args[1] + e.args[2] + b'CRASH' + else: + output_mupy = b'CRASH' # canonical form for all ports/platforms is to use \n for end-of-line output_mupy = output_mupy.replace(b'\r\n', b'\n') @@ -298,8 +300,12 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): skip_tests.add('thread/stress_recurse.py') # has reliability issues if upy_float_precision == 0: + skip_tests.add('extmod/uctypes_le_float.py') + skip_tests.add('extmod/uctypes_native_float.py') + skip_tests.add('extmod/uctypes_sizeof_float.py') skip_tests.add('extmod/ujson_dumps_float.py') skip_tests.add('extmod/ujson_loads_float.py') + skip_tests.add('extmod/urandom_extra_float.py') skip_tests.add('misc/rge_sm.py') if upy_float_precision < 32: skip_tests.add('float/float2int_intbig.py') # requires fp32, there's float2int_fp30_intbig.py instead @@ -348,6 +354,16 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): skip_tests.add('basics/subclass_native_init.py')# native subclassing corner cases not support skip_tests.add('misc/rge_sm.py') # too large skip_tests.add('micropython/opt_level.py') # don't assume line numbers are stored + elif args.target == 'nrf': + skip_tests.add('basics/memoryview1.py') # no item assignment for memoryview + skip_tests.add('extmod/ticks_diff.py') # unimplemented: utime.ticks_diff + skip_tests.add('extmod/time_ms_us.py') # unimplemented: utime.ticks_ms + skip_tests.add('extmod/urandom_basic.py') # unimplemented: urandom.seed + skip_tests.add('micropython/opt_level.py') # no support for line numbers + skip_tests.add('misc/non_compliant.py') # no item assignment for bytearray + for t in tests: + if t.startswith('basics/io_'): + skip_tests.add(t) # Some tests are known to fail on 64-bit machines if pyb is None and platform.architecture()[0] == '64bit': @@ -360,31 +376,21 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): # Some tests are known to fail with native emitter # Remove them from the below when they work if args.emit == 'native': - skip_tests.update({'basics/%s.py' % t for t in 'gen_yield_from gen_yield_from_close gen_yield_from_ducktype gen_yield_from_exc gen_yield_from_executing gen_yield_from_iter gen_yield_from_send gen_yield_from_stopped gen_yield_from_throw gen_yield_from_throw2 gen_yield_from_throw3 generator1 generator2 generator_args generator_close generator_closure generator_exc generator_pend_throw generator_return generator_send'.split()}) # require yield + skip_tests.update({'basics/%s.py' % t for t in 'gen_yield_from gen_yield_from_close gen_yield_from_ducktype gen_yield_from_exc gen_yield_from_executing gen_yield_from_iter gen_yield_from_send gen_yield_from_stopped gen_yield_from_throw gen_yield_from_throw2 gen_yield_from_throw3 generator1 generator2 generator_args generator_close generator_closure generator_exc generator_name generator_pend_throw generator_return generator_send'.split()}) # require yield skip_tests.update({'basics/%s.py' % t for t in 'bytes_gen class_store_class globals_del string_join gen_stack_overflow'.split()}) # require yield - skip_tests.update({'basics/async_%s.py' % t for t in 'def await await2 for for2 with with2 coroutine'.split()}) # require yield + skip_tests.update({'basics/async_%s.py' % t for t in 'def await await2 for for2 with with2 with_break with_return coroutine'.split()}) # require yield skip_tests.update({'basics/%s.py' % t for t in 'try_reraise try_reraise2'.split()}) # require raise_varargs - skip_tests.update({'basics/%s.py' % t for t in 'with_break with_continue with_return'.split()}) # require complete with support - skip_tests.add('basics/array_construct2.py') # requires generators - skip_tests.add('basics/bool1.py') # seems to randomly fail - skip_tests.add('basics/builtin_hash_gen.py') # requires yield - skip_tests.add('basics/class_bind_self.py') # requires yield skip_tests.add('basics/del_deref.py') # requires checking for unbound local skip_tests.add('basics/del_local.py') # requires checking for unbound local skip_tests.add('basics/exception_chain.py') # raise from is not supported - skip_tests.add('basics/for_range.py') # requires yield_value - skip_tests.add('basics/try_finally_loops.py') # requires proper try finally code - skip_tests.add('basics/try_finally_return.py') # requires proper try finally code - skip_tests.add('basics/try_finally_return2.py') # requires proper try finally code + skip_tests.add('basics/scope_implicit.py') # requires checking for unbound local + skip_tests.add('basics/try_finally_return2.py') # requires raise_varargs skip_tests.add('basics/unboundlocal.py') # requires checking for unbound local - skip_tests.add('import/gen_context.py') # requires yield_value skip_tests.add('misc/features.py') # requires raise_varargs - skip_tests.add('misc/rge_sm.py') # requires yield skip_tests.add('misc/print_exception.py') # because native doesn't have proper traceback info skip_tests.add('misc/sys_exc_info.py') # sys.exc_info() is not supported for native skip_tests.add('micropython/emg_exc.py') # because native doesn't have proper traceback info skip_tests.add('micropython/heapalloc_traceback.py') # because native doesn't have proper traceback info - skip_tests.add('micropython/heapalloc_iter.py') # requires generators skip_tests.add('micropython/schedule.py') # native code doesn't check pending events skip_tests.add('stress/gc_trace.py') # requires yield skip_tests.add('stress/recursive_gen.py') # requires yield @@ -403,8 +409,8 @@ def run_tests(pyb, tests, args, base_path=".", num_threads=1): if verdict == "exclude": return - test_basename = os.path.basename(test_file) - test_name = os.path.splitext(test_basename)[0] + test_basename = test_file.replace('..', '_').replace('./', '').replace('/', '_') + test_name = os.path.splitext(os.path.basename(test_file))[0] is_native = test_name.startswith("native_") or test_name.startswith("viper_") is_endian = test_name.endswith("_endian") is_int_big = test_name.startswith("int_big") or test_name.endswith("_intbig") @@ -560,10 +566,12 @@ the last matching regex is used: cmd_parser.add_argument('files', nargs='*', help='input test files') args = cmd_parser.parse_args() - EXTERNAL_TARGETS = ('pyboard', 'wipy', 'esp8266', 'esp32', 'minimal') + EXTERNAL_TARGETS = ('pyboard', 'wipy', 'esp8266', 'esp32', 'minimal', 'nrf') if args.target == 'unix' or args.list_tests: pyb = None elif args.target in EXTERNAL_TARGETS: + global pyboard + sys.path.append('../tools') import pyboard pyb = pyboard.Pyboard(args.device, args.baudrate, args.user, args.password) pyb.enter_raw_repl() @@ -575,7 +583,7 @@ the last matching regex is used: if args.target == 'pyboard': # run pyboard tests test_dirs = ('basics', 'micropython', 'float', 'misc', 'stress', 'extmod', 'pyb', 'pybnative', 'inlineasm') - elif args.target in ('esp8266', 'esp32', 'minimal'): + elif args.target in ('esp8266', 'esp32', 'minimal', 'nrf'): test_dirs = ('basics', 'micropython', 'float', 'misc', 'extmod') elif args.target == 'wipy': # run WiPy tests diff --git a/tests/run-tests-exp.py b/tests/run-tests-exp.py index 3af8feae7c713..34c6f650f83b6 100644 --- a/tests/run-tests-exp.py +++ b/tests/run-tests-exp.py @@ -9,12 +9,9 @@ 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 @@ def should_skip(test): 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 @@ def should_skip(test): 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 a8f50c4656df7..1ca1794edec38 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 36db9bb7e89d0..73d3a5b51d601 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 72dc7b62769d7..f952ad36a67c8 100644 --- a/tests/stress/gc_trace.py +++ b/tests/stress/gc_trace.py @@ -12,6 +12,8 @@ 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 227f48396ad47..c2d831bb8240a 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 0e0d3914ee9d5..8c2139765847d 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 5015c3f9cfaca..9b52e0c01643c 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 563fce39debb0..0840dcafba726 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 2ecfbe1092811..8ba91cbde380a 100644 --- a/tests/thread/mutate_instance.py +++ b/tests/thread/mutate_instance.py @@ -9,25 +9,28 @@ # 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 @@ def th(n, lo, hi): # 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 d70e8a8a388c7..8ce15c0852017 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 c4529f3562d20..61169b8aa97a6 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 ebf7af371b1cf..3191192a4d430 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 @@ def set_key(self, key): 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 @@ def apply_to(self, data): idx += ln self.state_pos += n + ################################################################## # test code @@ -209,6 +462,7 @@ def apply_to(self, data): import time import _thread + class LockedCounter: def __init__(self): self.lock = _thread.allocate_lock() @@ -219,8 +473,10 @@ def add(self, val): 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 2399746ccab93..eda768fa7b5a3 100644 --- a/tests/thread/stress_create.py +++ b/tests/thread/stress_create.py @@ -6,9 +6,11 @@ import time import _thread + def thread_entry(n): pass + thread_num = 0 while thread_num < 500: try: @@ -19,4 +21,4 @@ def thread_entry(n): # 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 206cf1a860120..41dfa5f3766d8 100644 --- a/tests/thread/stress_heap.py +++ b/tests/thread/stress_heap.py @@ -11,9 +11,11 @@ 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 8edee246ad14e..b7a1288211dc5 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 @@ def 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 e00a16bd2600a..3c3a1e8be9620 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 @@ def thread_entry(): # 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 35cb32441204e..2863e1dec12a4 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 ad7b01d89bb1c..6179716d14e6c 100644 --- a/tests/thread/thread_exit1.py +++ b/tests/thread/thread_exit1.py @@ -10,12 +10,14 @@ 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 6bff8a1736e06..ba9852b5c28f0 100644 --- a/tests/thread/thread_exit2.py +++ b/tests/thread/thread_exit2.py @@ -10,12 +10,14 @@ 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 2ea189161503a..4e4faeaf89f2c 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 9a6f89ff5f7e2..1ba342e2b6413 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 c2d7c9d1ed165..e7066402cabca 100644 --- a/tests/thread/thread_lock1.py +++ b/tests/thread/thread_lock1.py @@ -38,11 +38,11 @@ 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 4ef912dff5240..c43b4b18d148e 100644 --- a/tests/thread/thread_lock2.py +++ b/tests/thread/thread_lock2.py @@ -12,15 +12,17 @@ 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 35808d99cbd71..32d0c54b59e40 100644 --- a/tests/thread/thread_lock3.py +++ b/tests/thread/thread_lock3.py @@ -10,16 +10,18 @@ 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 440f3e90c68ed..7637d10b9659f 100644 --- a/tests/thread/thread_lock4.py +++ b/tests/thread/thread_lock4.py @@ -10,12 +10,14 @@ 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 dccfb7f517180..2099f94bdbf5c 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 @@ def th(base, n): 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 de339ad7f8ee1..87f8b51e2690b 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 2c749e6883bf8..dbe18f9875b7c 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 d5aa99f977622..d81d537399179 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 @@ 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 e7189fafbc198..0c6e7a92cd27b 100644 --- a/tests/thread/thread_stacksize1.py +++ b/tests/thread/thread_stacksize1.py @@ -8,20 +8,23 @@ 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 @@ def thread_entry(): # 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 94df6dc625f60..f08ff05a8eeac 100644 --- a/tests/thread/thread_start1.py +++ b/tests/thread/thread_start1.py @@ -10,16 +10,19 @@ 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 9412bb6183331..40f8a05227bad 100644 --- a/tests/thread/thread_start2.py +++ b/tests/thread/thread_start2.py @@ -10,11 +10,13 @@ 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 @@ def thread_entry(a0, a1, a2, a3): 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 8c45f91faf723..1a5b933c89e48 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 3a35ce8948dba..072e049fde416 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,35 @@ # 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") +try: + str(b"\xf0\xe0\xed\xe8", "utf8") +except UnicodeError: + print("UnicodeError") diff --git a/tests/unicode/unicode_id.py b/tests/unicode/unicode_id.py index 10f540c5034ca..3a58e3f72b5e7 100644 --- a/tests/unicode/unicode_id.py +++ b/tests/unicode/unicode_id.py @@ -14,14 +14,19 @@ 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 47cfa1c2d7cdf..73577050bf55b 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 bf8505a31aced..1a60e7be4a619 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 e9b152473c05b..42211d0b0558d 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 a2f434de5806e..50289100779ec 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 13721f1f479c3..e31eece774228 100644 --- a/tests/unix/extra_coverage.py +++ b/tests/unix/extra_coverage.py @@ -13,33 +13,33 @@ 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 @@ # 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 23b058bcec2c4..21bfccf251eb8 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 c92a39bcdc821..d0393989651b3 100644 --- a/tests/unix/ffi_float.py +++ b/tests/unix/ffi_float.py @@ -16,17 +16,25 @@ def ffi_open(names): err = e raise err -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)) +libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) + +try: + strtof = libc.func("f", "strtof", "sp") +except OSError: + # Some libc's (e.g. Android's Bionic) define strtof as macro/inline func + # in terms of strtod(). + print("SKIP") + raise SystemExit + +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 721eb4d192f17..bbed6966627e1 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 deleted file mode 100644 index 6fd4373dbd8df..0000000000000 --- a/tests/wipy/adc.py +++ /dev/null @@ -1,115 +0,0 @@ -''' -ADC test for the CC3200 based boards. -''' - -from machine import ADC -import os - -mch = os.uname().machine -if 'LaunchPad' in mch: - adc_pin = 'GP5' - adc_channel = 3 -elif 'WiPy' in mch: - adc_pin = 'GP3' - adc_channel = 1 -else: - raise Exception('Board not supported!') - -adc = ADC(0) -print(adc) -adc = ADC() -print(adc) -adc = ADC(0, bits=12) -print(adc) - -apin = adc.channel(adc_channel) -print(apin) -apin = adc.channel(id=adc_channel) -print(apin) -apin = adc.channel(adc_channel, pin=adc_pin) -print(apin) -apin = adc.channel(id=adc_channel, pin=adc_pin) -print(apin) - -print(apin.value() > 3000) -print(apin() > 3000) - -# de-init must work -apin.deinit() -print(apin) - -adc.deinit() -print(adc) -print(apin) -adc.init() -print(adc) -print(apin) -apin.init() -print(apin) -print(apin() > 3000) - -# check for memory leaks... -for i in range (0, 1000): - adc = ADC() - apin = adc.channel(adc_channel) - -# next ones should raise -try: - adc = ADC(bits=17) -except: - print('Exception') - -try: - adc = ADC(id=1) -except: - print('Exception') - -try: - adc = ADC(0, 16) -except: - print('Exception') - -adc = ADC() -try: - apin = adc.channel(4) -except: - print('Exception') - -try: - apin = adc.channel(-1) -except: - print('Exception') - -try: - apin = adc.channel(0, pin='GP3') -except: - print('Exception') - -apin = adc.channel(1) -apin.deinit() -try: - apin() -except: - print('Exception') - -try: - apin.value() -except: - print('Exception') - -adc.deinit() -try: - apin.value() -except: - print('Exception') - -try: - apin = adc.channel(1) -except: - print('Exception') - -# re-init must work -adc.init() -apin.init() -print(apin) -print(apin() > 3000) diff --git a/tests/wipy/adc.py.exp b/tests/wipy/adc.py.exp deleted file mode 100644 index a65cf4963b387..0000000000000 --- a/tests/wipy/adc.py.exp +++ /dev/null @@ -1,28 +0,0 @@ -ADC(0, bits=12) -ADC(0, bits=12) -ADC(0, bits=12) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -ADCChannel(1, pin=GP3) -True -True -ADCChannel(1) -ADC(0) -ADCChannel(1) -ADC(0, bits=12) -ADCChannel(1) -ADCChannel(1, pin=GP3) -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -ADCChannel(1, pin=GP3) -True diff --git a/tests/wipy/modwipy.py b/tests/wipy/modwipy.py deleted file mode 100644 index 7571af0753178..0000000000000 --- a/tests/wipy/modwipy.py +++ /dev/null @@ -1,21 +0,0 @@ -''' -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!') - -print(wipy.heartbeat() == True) -wipy.heartbeat(False) -print(wipy.heartbeat() == False) -wipy.heartbeat(True) -print(wipy.heartbeat() == True) - -try: - wipy.heartbeat(True, 1) -except: - print('Exception') diff --git a/tests/wipy/modwipy.py.exp b/tests/wipy/modwipy.py.exp deleted file mode 100644 index 52eeb534ee22c..0000000000000 --- a/tests/wipy/modwipy.py.exp +++ /dev/null @@ -1,4 +0,0 @@ -True -True -True -Exception diff --git a/tests/wipy/os.py b/tests/wipy/os.py deleted file mode 100644 index 0596a16b5290b..0000000000000 --- a/tests/wipy/os.py +++ /dev/null @@ -1,164 +0,0 @@ -''' -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') -else: - raise Exception('Board not supported!') - -sd = SD(pins=sd_pins) - -os.mount(sd, '/sd') -os.mkfs('/sd') -os.chdir('/flash') -print(os.listdir()) - -os.chdir('/sd') -print(os.listdir()) - -# create a test directory in flash -os.mkdir('/flash/test') -os.chdir('/flash/test') -print(os.getcwd()) -os.chdir('..') -print(os.getcwd()) -os.chdir('test') -print(os.getcwd()) -# create a new file -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') -# check that we can write and read it correctly -print(r == test_bytes) -f.close() -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') - -# create a test directory in the sd card -os.mkdir('/sd/test') -os.chdir('/sd/test') -print(os.getcwd()) -os.chdir('..') -print(os.getcwd()) -os.chdir('test') -print(os.getcwd()) -# create a new file -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') -# 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) - -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.mkfs(sd) -os.mount(sd, '/sd') -print(os.listdir('/')) -os.chdir('/flash') - -# next ones must raise -sd.deinit() -try: - os.listdir('/sd') -except: - print('Exception') - -#re-initialization must work -sd.init() -print(os.listdir('/sd')) - -try: - os.mount(sd, '/sd') -except: - print('Exception') - -try: - os.mount(sd, '/sd2') -except: - print('Exception') - -os.unmount('/sd') -try: - os.listdir('/sd') -except: - print('Exception') - -try: - os.unmount('/flash') -except: - print('Exception') - -try: - os.unmount('/something') -except: - print('Exception') - -try: - os.unmount('something') -except: - print('Exception') - -try: - os.mkfs('flash') # incorrect path format -except: - print('Exception') - -try: - os.remove('/flash/nofile.txt') -except: - print('Exception') - -try: - os.rename('/flash/nofile.txt', '/flash/nofile2.txt') -except: - print('Exception') - -try: - os.chdir('/flash/nodir') -except: - print('Exception') - -try: - os.listdir('/flash/nodir') -except: - print('Exception') - -os.mount(sd, '/sd') -print(os.listdir('/')) -os.unmount('/sd') diff --git a/tests/wipy/os.py.exp b/tests/wipy/os.py.exp deleted file mode 100644 index a0f01e35e1b92..0000000000000 --- a/tests/wipy/os.py.exp +++ /dev/null @@ -1,32 +0,0 @@ -['main.py', 'sys', 'lib', 'cert', 'boot.py'] -[] -/flash/test -/flash -/flash/test -True -True -['newtest.txt'] -['main.py', 'sys', 'lib', 'cert', 'boot.py', 'newtest'] -/sd/test -/sd -/sd/test -True -True -True -True -['flash', 'sd'] -['flash'] -['flash', 'sd'] -[] -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -['flash', 'sd'] diff --git a/tests/wipy/pin.py b/tests/wipy/pin.py deleted file mode 100644 index 666ecb66bc680..0000000000000 --- a/tests/wipy/pin.py +++ /dev/null @@ -1,181 +0,0 @@ -""" -This test need a set of pins which can be set as inputs and have no external -pull up or pull down connected. -GP12 and GP17 must be connected together -""" -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'] - 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'] - max_af_idx = 15 -else: - raise Exception('Board not supported!') - -# test initial value -p = Pin('GP12', Pin.IN) -Pin('GP17', Pin.OUT, value=1) -print(p() == 1) -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: - pin = Pin(p, mode=Pin.IN, pull=pull) - for p in pin_map: - print(pin()) - -def test_pin_af(): - for p in pin_map: - for af in Pin(p).alt_list(): - if af[1] <= max_af_idx: - 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 -test_pin_read(Pin.PULL_UP) -test_pin_read(Pin.PULL_DOWN) - -# test all constructor combinations -pin = Pin(pin_map[0]) -pin = Pin(pin_map[0], mode=Pin.IN) -pin = Pin(pin_map[0], mode=Pin.OUT) -pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.PULL_DOWN) -pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OPEN_DRAIN, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_DOWN) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=None) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.MED_POWER) -pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) -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 init and printing -pin = Pin(pin_map[0]) -pin.init(mode=Pin.IN) -print(pin) -pin.init(Pin.IN, Pin.PULL_DOWN) -print(pin) -pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) -print(pin) -pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) -print(pin) - -# test value in OUT mode -pin = Pin(pin_map[0], mode=Pin.OUT) -pin.value(0) -pin.toggle() # test toggle -print(pin()) -pin.toggle() # test toggle again -print(pin()) -# test different value settings -pin(1) -print(pin.value()) -pin(0) -print(pin.value()) -pin.value(1) -print(pin()) -pin.value(0) -print(pin()) - -# test all getters and setters -pin = Pin(pin_map[0], mode=Pin.OUT) -# mode -print(pin.mode() == Pin.OUT) -pin.mode(Pin.IN) -print(pin.mode() == Pin.IN) -# pull -pin.pull(None) -print(pin.pull() == None) -pin.pull(Pin.PULL_DOWN) -print(pin.pull() == Pin.PULL_DOWN) -# drive -pin.drive(Pin.MED_POWER) -print(pin.drive() == Pin.MED_POWER) -pin.drive(Pin.HIGH_POWER) -print(pin.drive() == Pin.HIGH_POWER) -# id -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 -except Exception: - print('Exception') - -try: - pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value -except Exception: - print('Exception') - -try: - pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value -except Exception: - print('Exception') - -try: - pin = Pin('A0', Pin.OUT, Pin.PULL_DOWN) # incorrect pin id -except Exception: - print('Exception') - -try: - pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode -except Exception: - print('Exception') - -try: - pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode -except Exception: - print('Exception') - -try: - pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af -except Exception: - print('Exception') - -try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af -except Exception: - print('Exception') - -try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af -except Exception: - print('Exception') - -try: - pin.mode(Pin.PULL_UP) # incorrect pin mode -except Exception: - print('Exception') - -try: - pin.pull(Pin.OUT) # incorrect pull -except Exception: - print('Exception') - -try: - pin.drive(Pin.IN) # incorrect drive strength -except Exception: - print('Exception') - -try: - pin.id('ABC') # id cannot be set -except Exception: - print('Exception') diff --git a/tests/wipy/pin.py.exp b/tests/wipy/pin.py.exp deleted file mode 100644 index 0e3dddcf2b1e5..0000000000000 --- a/tests/wipy/pin.py.exp +++ /dev/null @@ -1,60 +0,0 @@ -True -True -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -0 -Pin('GP23', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Pin('GP23', mode=Pin.IN, pull=Pin.PULL_DOWN, drive=Pin.MED_POWER, alt=-1) -Pin('GP23', mode=Pin.OUT, pull=Pin.PULL_UP, drive=Pin.LOW_POWER, alt=-1) -Pin('GP23', mode=Pin.OUT, pull=Pin.PULL_UP, drive=Pin.HIGH_POWER, alt=-1) -1 -0 -1 -0 -1 -0 -True -True -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/pin_irq.py b/tests/wipy/pin_irq.py deleted file mode 100644 index 875f1f9397f05..0000000000000 --- a/tests/wipy/pin_irq.py +++ /dev/null @@ -1,116 +0,0 @@ -''' -Pin IRQ test for the CC3200 based boards. -''' - -from machine import Pin -import machine -import os -import time - -mch = os.uname().machine -if 'LaunchPad' in mch: - pins = ['GP16', 'GP13'] -elif 'WiPy' in mch: - pins = ['GP16', 'GP13'] -else: - 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): - global pin_irq_count_trigger - global pin_irq_count_total - global _trigger - if _trigger & pin1_irq.flags(): - 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): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 5) -print(pin_irq_count_total == 5) - -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): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 100) -print(pin_irq_count_total == 100) - -pin1_irq.disable() -pin0(1) -pin_irq_count_trigger = 0 -pin_irq_count_total = 0 -_trigger = Pin.IRQ_FALLING -pin1_irq.init(trigger=_trigger, handler=pin_handler) -pin0(0) -time.sleep_us(50) -print(pin_irq_count_trigger == 1) -print(pin_irq_count_total == 1) -pin0(1) -time.sleep_us(50) -print(pin_irq_count_trigger == 1) -print(pin_irq_count_total == 1) - -# check the call method -pin1_irq() -print(pin_irq_count_trigger == 1) # no flags since the irq was manually triggered -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): - pin0.toggle() - time.sleep_ms(5) -print(pin_irq_count_trigger == 0) -print(pin_irq_count_total == 0) - -# test waking up from suspended mode on low level -pin0(0) -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') - -# test waking up from suspended mode on high level -pin0(1) -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') - -# check for memory leaks -for i in range(0, 1000): - pin0_irq = pin0.irq(trigger=_trigger, handler=pin_handler) - pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) - -# next ones must raise -try: - pin1_irq.init(trigger=123456, handler=pin_handler) -except: - print('Exception') - -try: - pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=1789456) -except: - print('Exception') - -try: - pin0_irq = pin0.irq(trigger=Pin.IRQ_RISING, wake=machine.SLEEP) # GP16 can't wake up from DEEPSLEEP -except: - print('Exception') - -pin0_irq.disable() -pin1_irq.disable() diff --git a/tests/wipy/pin_irq.py.exp b/tests/wipy/pin_irq.py.exp deleted file mode 100644 index 458bd956682ad..0000000000000 --- a/tests/wipy/pin_irq.py.exp +++ /dev/null @@ -1,19 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -Awake -True -Awake -Exception -Exception -Exception diff --git a/tests/wipy/reset/reset.py b/tests/wipy/reset/reset.py deleted file mode 100644 index 35a970c6734e5..0000000000000 --- a/tests/wipy/reset/reset.py +++ /dev/null @@ -1,17 +0,0 @@ -''' -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!') - -wdt = WDT(timeout=1000) -print(wdt) -time.sleep_ms(900) diff --git a/tests/wipy/reset/reset.py.exp b/tests/wipy/reset/reset.py.exp deleted file mode 100644 index 4b6cc11e0da70..0000000000000 --- a/tests/wipy/reset/reset.py.exp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/wipy/rtc.py b/tests/wipy/rtc.py deleted file mode 100644 index 2737ebe73a13e..0000000000000 --- a/tests/wipy/rtc.py +++ /dev/null @@ -1,117 +0,0 @@ -''' -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!') - -rtc = RTC() -print(rtc) -print(rtc.now()[:6]) - -rtc = RTC(datetime=(2015, 8, 29, 9, 0, 0, 0, None)) -print(rtc.now()[:6]) - -rtc.deinit() -print(rtc.now()[:6]) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -print(rtc.now()[:6]) -seconds = rtc.now()[5] -time.sleep_ms(1000) -print(rtc.now()[5] - seconds == 1) -seconds = rtc.now()[5] -time.sleep_ms(2000) -print(rtc.now()[5] - seconds == 2) - -# initialization with shorter tuples -rtc.init((2015, 9, 19, 8, 0, 0, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8, 0, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8, 0)) -print(rtc.now()[5]) -rtc.init((2015, 9, 19, 8)) -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)) -set_and_print((2000, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 1, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 12, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 13, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 0, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 1, 0, 0, None)) -set_and_print((2016, 12, 31, 23, 59, 0, 50, None)) -set_and_print((2016, 12, 31, 23, 59, 1, 900, None)) -set_and_print((2016, 12, 31, 23, 59, 59, 100, None)) -set_and_print((2048, 12, 31, 23, 59, 59, 99999, None)) - -rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) -rtc.alarm(0, 5000) -rtc.alarm(time=2000) -time.sleep_ms(1000) -left = rtc.alarm_left() -print(abs(left-1000) <= 10) -time.sleep_ms(1000) -print(rtc.alarm_left() == 0) -time.sleep_ms(100) -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) - -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) -rtc.alarm_cancel() -rtc.deinit() - -# next ones must raise -try: - rtc.alarm(5000) -except: - print('Exception') - -try: - rtc.alarm_left(1) -except: - print('Exception') - -try: - rtc.alarm_cancel(1) -except: - print('Exception') - -try: - rtc.alarm(5000) -except: - print('Exception') - -try: - rtc = RTC(200000000) -except: - print('Exception') - -try: - rtc = RTC((2015, 8, 29, 9, 0, 0, 0, None)) -except: - print('Exception') diff --git a/tests/wipy/rtc.py.exp b/tests/wipy/rtc.py.exp deleted file mode 100644 index 44f8f8b81c7df..0000000000000 --- a/tests/wipy/rtc.py.exp +++ /dev/null @@ -1,37 +0,0 @@ - -(2015, 1, 1, 0, 0, 0) -(2015, 8, 29, 9, 0, 0) -(2015, 1, 1, 0, 0, 0) -(2015, 8, 29, 9, 0, 0) -True -True -0 -0 -0 -0 -0 -(2000, 1, 1, 0, 0, 0) -(2000, 1, 31, 0, 0, 0) -(2000, 12, 31, 0, 0, 0) -(2016, 12, 31, 0, 0, 0) -(2016, 12, 31, 0, 0, 0) -(2016, 12, 31, 1, 0, 0) -(2016, 12, 31, 12, 0, 0) -(2016, 12, 31, 13, 0, 0) -(2016, 12, 31, 23, 0, 0) -(2016, 12, 31, 23, 1, 0) -(2016, 12, 31, 23, 59, 0) -(2016, 12, 31, 23, 59, 1) -(2016, 12, 31, 23, 59, 59) -(2048, 12, 31, 23, 59, 59) -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/sd.py b/tests/wipy/sd.py deleted file mode 100644 index c946e0c9f0beb..0000000000000 --- a/tests/wipy/sd.py +++ /dev/null @@ -1,45 +0,0 @@ -''' -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') -else: - raise Exception('Board not supported!') - -sd = SD(pins=sd_pins) -print(sd) -sd.deinit() -print(sd) -sd.init(sd_pins) -print(sd) - -sd = SD(0, pins=sd_pins) -sd = SD(id=0, pins=sd_pins) -sd = SD(0, sd_pins) - -# check for memory leaks -for i in range(0, 1000): - sd = sd = SD(0, pins=sd_pins) - -# next ones should raise -try: - sd = SD(pins=()) -except Exception: - print("Exception") - -try: - sd = SD(pins=('GP10', 'GP11', 'GP8')) -except Exception: - print("Exception") - -try: - sd = SD(pins=('GP10', 'GP11')) -except Exception: - print("Exception") diff --git a/tests/wipy/sd.py.exp b/tests/wipy/sd.py.exp deleted file mode 100644 index eaa5f08efb97b..0000000000000 --- a/tests/wipy/sd.py.exp +++ /dev/null @@ -1,6 +0,0 @@ - - - -Exception -Exception -Exception diff --git a/tests/wipy/skipped/rtc_irq.py b/tests/wipy/skipped/rtc_irq.py deleted file mode 100644 index ec3baa552426b..0000000000000 --- a/tests/wipy/skipped/rtc_irq.py +++ /dev/null @@ -1,89 +0,0 @@ -''' -RTC IRQ test for the CC3200 based boards. -''' - -from machine import RTC -import machine -import os -import time - -mch = os.uname().machine -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): - 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) - -# active mode -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 2) -rtc_irq_count = 0 -rtc.alarm(time=200, repeat=True) -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 5) - -rtc_irq_count = 0 -rtc.alarm(time=100, repeat=True) -time.sleep_ms(1000) -rtc.alarm_cancel() -print(rtc_irq_count == 10) - -# deep sleep mode -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=50, repeat=True) -rtc_irq.init(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP | machine.IDLE) -while rtc_irq_count < 3: - machine.sleep() -print(rtc_irq_count == 3) - -# no repetition -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=100, repeat=False) -time.sleep_ms(250) -print(rtc_irq_count == 1) - -rtc.alarm_cancel() -t0 = rtc_ticks_ms(rtc) -rtc.alarm(time=500, repeat=False) -machine.sleep() -t1 = rtc_ticks_ms(rtc) -print(abs(t1 - t0 - 500) < 20) - -# deep sleep repeated mode -rtc.alarm_cancel() -rtc_irq_count = 0 -rtc.alarm(time=500, repeat=True) -t0 = rtc_ticks_ms(rtc) -rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP) -while rtc_irq_count < 3: - machine.sleep() - t1 = rtc_ticks_ms(rtc) - print(abs(t1 - t0 - (500 * rtc_irq_count)) < 25) - -# next ones must raise -try: - rtc_irq = rtc.irq(trigger=10, handler=alarm_handler) -except: - print('Exception') - -try: - rtc_irq = rtc.irq(trigger=RTC.ALARM0, wake=1789456) -except: - print('Exception') diff --git a/tests/wipy/skipped/rtc_irq.py.exp b/tests/wipy/skipped/rtc_irq.py.exp deleted file mode 100644 index a3eebc2d11da5..0000000000000 --- a/tests/wipy/skipped/rtc_irq.py.exp +++ /dev/null @@ -1,11 +0,0 @@ -True -True -True -True -True -True -True -True -True -Exception -Exception diff --git a/tests/wipy/time.py b/tests/wipy/time.py deleted file mode 100644 index e6237de356f63..0000000000000 --- a/tests/wipy/time.py +++ /dev/null @@ -1,75 +0,0 @@ -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 - for year in range(2000, 2049): - print("Testing %d" % year) - yday = 1 - for month in range(1, 13): - if month == 2 and is_leap(year): - DAYS_PER_MONTH[2] = 29 - else: - DAYS_PER_MONTH[2] = 28 - 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)) - 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)) - return - seconds += 86400 - if yday != tuple[7]: - 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)) - 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) - 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)) - -t1 = time.time() -time.sleep(2) -t2 = time.time() -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) - -t1 = time.ticks_us() -time.sleep_us(1000) -t2 = time.ticks_us() -print(time.ticks_diff(t1, t2) < 1500) - -print(time.ticks_diff(time.ticks_cpu(), time.ticks_cpu()) < 16384) diff --git a/tests/wipy/time.py.exp b/tests/wipy/time.py.exp deleted file mode 100644 index 24d798f92922e..0000000000000 --- a/tests/wipy/time.py.exp +++ /dev/null @@ -1,65 +0,0 @@ -Testing 2000 -Testing 2001 -Testing 2002 -Testing 2003 -Testing 2004 -Testing 2005 -Testing 2006 -Testing 2007 -Testing 2008 -Testing 2009 -Testing 2010 -Testing 2011 -Testing 2012 -Testing 2013 -Testing 2014 -Testing 2015 -Testing 2016 -Testing 2017 -Testing 2018 -Testing 2019 -Testing 2020 -Testing 2021 -Testing 2022 -Testing 2023 -Testing 2024 -Testing 2025 -Testing 2026 -Testing 2027 -Testing 2028 -Testing 2029 -Testing 2030 -Testing 2031 -Testing 2032 -Testing 2033 -Testing 2034 -Testing 2035 -Testing 2036 -Testing 2037 -Testing 2038 -Testing 2039 -Testing 2040 -Testing 2041 -Testing 2042 -Testing 2043 -Testing 2044 -Testing 2045 -Testing 2046 -Testing 2047 -Testing 2048 -time.localtime( 0 ) returned (2000, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( 1 ) returned (2000, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( 59 ) returned (2000, 1, 1, 0, 0, 59, 5, 1) (pass) -time.localtime( 60 ) returned (2000, 1, 1, 0, 1, 0, 5, 1) (pass) -time.localtime( 3599 ) returned (2000, 1, 1, 0, 59, 59, 5, 1) (pass) -time.localtime( 3600 ) returned (2000, 1, 1, 1, 0, 0, 5, 1) (pass) -time.localtime( -1 ) returned (1999, 12, 31, 23, 59, 59, 4, 365) (pass) -time.localtime( 447549467 ) returned (2014, 3, 7, 23, 17, 47, 4, 66) (pass) -time.localtime( -940984933 ) returned (1970, 3, 7, 23, 17, 47, 5, 66) (pass) -time.localtime( -1072915199 ) returned (1966, 1, 1, 0, 0, 1, 5, 1) (pass) -time.localtime( -1072915200 ) returned (1966, 1, 1, 0, 0, 0, 5, 1) (pass) -time.localtime( -1072915201 ) returned (1965, 12, 31, 23, 59, 59, 4, 365) (pass) -True -True -True -True diff --git a/tests/wipy/timer.py b/tests/wipy/timer.py deleted file mode 100644 index f62899b472fa3..0000000000000 --- a/tests/wipy/timer.py +++ /dev/null @@ -1,117 +0,0 @@ -''' -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') -else: - raise Exception('Board not supported!') - -for i in range(4): - tim = Timer(i, mode=Timer.PERIODIC) - print(tim) - ch = tim.channel(Timer.A, freq=5) - print(ch) - ch = tim.channel(Timer.B, freq=5) - print(ch) - tim = Timer(i, mode=Timer.ONE_SHOT) - print(tim) - ch = tim.channel(Timer.A, freq=50) - print(ch) - ch = tim.channel(Timer.B, freq=50) - print(ch) - tim = Timer(i, mode=Timer.PWM) - print(tim) - ch = tim.channel(Timer.A, freq=50000, duty_cycle=2000, polarity=Timer.POSITIVE) - print(ch) - ch = tim.channel(Timer.B, freq=50000, duty_cycle=8000, polarity=Timer.NEGATIVE) - print(ch) - tim.deinit() - print(tim) - -for i in range(4): - tim = Timer(i, mode=Timer.PERIODIC) - tim.deinit() - - -class TimerTest: - def __init__(self): - self.tim = Timer(0, mode=Timer.PERIODIC) - self.int_count = 0 - - 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) -ch.irq(handler=timer_test.timer_isr, trigger=Timer.TIMEOUT) -time.sleep_ms(1001) -print(timer_test.int_count == 5) - -ch.freq(100) -timer_test.int_count = 0 -time.sleep_ms(1001) -print(timer_test.int_count == 100) - -ch.freq(1000) -time.sleep_ms(1500) -timer_test.int_count = 0 -time.sleep_ms(2000) -print(timer_test.int_count == 2000) - -timer_test.tim.deinit() -timer_test.tim.init(mode=Timer.ONE_SHOT) -ch = timer_test.tim.channel(Timer.A, period=100000) -ch.irq(handler=timer_test.timer_isr, trigger=Timer.TIMEOUT) -timer_test.int_count = 0 -time.sleep_ms(101) -print(timer_test.int_count == 1) -time.sleep_ms(101) -print(timer_test.int_count == 1) -timer_test.tim.deinit() -print(timer_test.tim) - -# 32 bit modes -tim = Timer(0, mode=Timer.PERIODIC, width=32) -ch = tim.channel(Timer.A | Timer.B, period=5000000) - -# check for memory leaks... -for i in range(1000): - tim = Timer(0, mode=Timer.PERIODIC) - ch = tim.channel(Timer.A, freq=5) - -# next ones must fail -try: - tim = Timer(0, mode=12) -except: - print('Exception') - -try: - tim = Timer(4, mode=Timer.ONE_SHOT) -except: - print('Exception') - -try: - tim = Timer(0, mode=Timer.PWM, width=32) -except: - print('Exception') - -tim = Timer(0, mode=Timer.PWM) - -try: - ch = tim.channel(TIMER_A | TIMER_B, freq=10) -except: - print('Exception') - -try: - ch = tim.channel(TIMER_A, freq=4) -except: - print('Exception') diff --git a/tests/wipy/timer.py.exp b/tests/wipy/timer.py.exp deleted file mode 100644 index 972d8198cc868..0000000000000 --- a/tests/wipy/timer.py.exp +++ /dev/null @@ -1,52 +0,0 @@ -Timer(0, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(0, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(0, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(0, mode=Timer.PWM) -Timer(1, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(1, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(1, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(1, mode=Timer.PWM) -Timer(2, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(2, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(2, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(2, mode=Timer.PWM) -Timer(3, mode=Timer.PERIODIC) -timer.channel(Timer.A, freq=5) -timer.channel(Timer.B, freq=5) -Timer(3, mode=Timer.ONE_SHOT) -timer.channel(Timer.A, freq=50) -timer.channel(Timer.B, freq=50) -Timer(3, mode=Timer.PWM) -timer.channel(Timer.A, freq=50000, polarity=Timer.POSITIVE, duty_cycle=20.00) -timer.channel(Timer.B, freq=50000, polarity=Timer.NEGATIVE, duty_cycle=80.00) -Timer(3, mode=Timer.PWM) -True -True -True -True -True -True -Timer(0, mode=Timer.ONE_SHOT) -Exception -Exception -Exception -Exception -Exception diff --git a/tests/wipy/uart.py b/tests/wipy/uart.py deleted file mode 100644 index d8b405f77046a..0000000000000 --- a/tests/wipy/uart.py +++ /dev/null @@ -1,158 +0,0 @@ -''' -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 -import os -import time - -mch = os.uname().machine -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_id_range = range(0, 2) - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] -else: - raise Exception('Board not supported!') - -# just in case we have the repl duplicated on any of the uarts -os.dupterm(None) - -for uart_id in uart_id_range: - uart = UART(uart_id, 38400) - print(uart) - uart.init(57600, 8, None, 1, pins=uart_pins[uart_id][0]) - uart.init(baudrate=9600, stop=2, parity=UART.EVEN, pins=uart_pins[uart_id][1]) - uart.init(baudrate=115200, parity=UART.ODD, stop=0, pins=uart_pins[uart_id][0]) - uart = UART(baudrate=1000000) - uart.sendbreak() - -uart = UART(baudrate=1000000) -uart = UART() -print(uart) -uart = UART(baudrate=38400, pins=('GP12', 'GP13')) -print(uart) -uart = UART(pins=('GP12', 'GP13')) -print(uart) -uart = UART(pins=(None, 'GP17')) -print(uart) -uart = UART(baudrate=57600, pins=('GP16', 'GP17')) -print(uart) - -# now it's time for some loopback tests between the uarts -uart0 = UART(0, 1000000, pins=uart_pins[0][0]) -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(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') -buf = bytearray(3) -print(uart1.readinto(buf, 1) == 1) -print(buf) -print(uart1.readinto(buf) == 2) -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 -print(uart1.any() == 10) -print(uart1.readline() == b'1234567890') -print(uart1.any() == 0) - -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) -print(uart0.read() == None) - -# rx only mode -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') - -# leave pins as they were (rx only mode) -uart0 = UART(0, 1000000, pins=None) -print(uart0.write(b'123456') == 6) -print(uart1.read() == None) -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(uart1.read() == None) -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): - uart0 = UART(0, 1000000) - uart1 = UART(1, 1000000) - -# next ones must raise -try: - UART(0, 9600, parity=None, pins=('GP12', 'GP13', 'GP7')) -except Exception: - print('Exception') - -try: - UART(0, 9600, parity=UART.ODD, pins=('GP12', 'GP7')) -except Exception: - print('Exception') - -uart0 = UART(0, 1000000) -uart0.deinit() -try: - uart0.any() -except Exception: - print('Exception') - -try: - uart0.read() -except Exception: - print('Exception') - -try: - uart0.write('abc') -except Exception: - print('Exception') - -try: - uart0.sendbreak('abc') -except Exception: - print('Exception') - -try: - UART(2, 9600) -except Exception: - print('Exception') - -for uart_id in uart_id_range: - uart = UART(uart_id, 1000000) - uart.deinit() - # test printing an unitialized uart - print(uart) - # initialize it back and check that it works again - uart.init(115200) - print(uart) - uart.read() diff --git a/tests/wipy/uart.py.exp b/tests/wipy/uart.py.exp deleted file mode 100644 index c8aeb77effefd..0000000000000 --- a/tests/wipy/uart.py.exp +++ /dev/null @@ -1,52 +0,0 @@ -UART(0, baudrate=38400, bits=8, parity=None, stop=1) -UART(1, baudrate=38400, bits=8, parity=None, stop=1) -UART(0, baudrate=9600, bits=8, parity=None, stop=1) -UART(0, baudrate=38400, bits=8, parity=None, stop=1) -UART(0, baudrate=9600, bits=8, parity=None, stop=1) -UART(1, baudrate=9600, bits=8, parity=None, stop=1) -UART(1, baudrate=57600, bits=8, parity=None, stop=1) -UART(0, baudrate=1000000, bits=8, parity=None, stop=1) -UART(1, baudrate=1000000, bits=8, parity=None, stop=1) -True -True -True -True -True -True -True -bytearray(b'1\x00\x00') -True -bytearray(b'23\x00') -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Pin('GP12', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Pin('GP13', mode=Pin.IN, pull=None, drive=Pin.MED_POWER, alt=-1) -Exception -Exception -Exception -Exception -Exception -Exception -Exception -UART(0) -UART(0, baudrate=115200, bits=8, parity=None, stop=1) -UART(1) -UART(1, baudrate=115200, bits=8, parity=None, stop=1) diff --git a/tests/wipy/uart_irq.py b/tests/wipy/uart_irq.py deleted file mode 100644 index d4cd900585ef7..0000000000000 --- a/tests/wipy/uart_irq.py +++ /dev/null @@ -1,148 +0,0 @@ -''' -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')]] -else: - raise Exception('Board not supported!') - -# just in case we have stdio duplicated on any of the uarts -os.dupterm(None) - -uart0 = UART(0, 1000000, pins=uart_pins[0][0]) -uart1 = UART(1, 1000000, pins=uart_pins[1][0]) - -uart0_int_count = 0 -uart1_int_count = 0 - -def uart0_handler (uart_o): - global uart0_irq - global uart0_int_count - if (uart0_irq.flags() & UART.RX_ANY): - uart0_int_count += 1 - -def uart1_handler (uart_o): - global uart1_irq - global uart1_int_count - 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') -# 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) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') - -uart1.write(b'12345') -# wait for the characters to be received -while not uart0.any(): - pass - -time.sleep_us(100) -print(uart0.any() == 5) -print(uart0_int_count > 0) -print(uart0_irq.flags() == 0) -print(uart1_irq.flags() == 0) -print(uart0.read() == b'12345') - -# do it again -uart1_int_count = 0 -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) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') - -# disable the interrupt -uart1_irq.disable() -# do it again -uart1_int_count = 0 -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_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') - -# enable the interrupt -uart1_irq.enable() -# do it again -uart1_int_count = 0 -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) -print(uart1_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') - -uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler -# do it again -uart1_int_count = 0 -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_irq.flags() == 0) -print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') - -# check for memory leaks -for i in range(0, 1000): - uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) - uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) - -# next ones must raise -try: - uart0_irq = uart0.irq(trigger=100, handler=uart0_handler) -except: - print('Exception') - -try: - uart0_irq = uart0.irq(trigger=0) -except: - print('Exception') - -try: - uart0_irq = uart0.irq(trigger=UART.RX_ANY, wake=Sleep.SUSPENDED) -except: - print('Exception') - -uart0_irq.disable() -uart1_irq.disable() diff --git a/tests/wipy/uart_irq.py.exp b/tests/wipy/uart_irq.py.exp deleted file mode 100644 index b165e824a0149..0000000000000 --- a/tests/wipy/uart_irq.py.exp +++ /dev/null @@ -1,33 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Exception -Exception -Exception diff --git a/tests/wipy/wdt.py b/tests/wipy/wdt.py deleted file mode 100644 index a894b88fd8f2f..0000000000000 --- a/tests/wipy/wdt.py +++ /dev/null @@ -1,38 +0,0 @@ -''' -WDT test for the CC3200 based boards -''' - -from machine import WDT -import time - -# test the invalid cases first -try: - wdt = WDT(1) -except Exception: - print("Exception") - -try: - wdt = WDT(0, 500) -except Exception: - print("Exception") - -try: - wdt = WDT(1, timeout=2000) -except Exception: - print("Exception") - -wdt = WDT(timeout=1000) -print(wdt) - -try: - wdt = WDT(0, timeout=2000) -except Exception: - print("Exception") - -time.sleep_ms(500) -wdt.feed() -print(wdt) -time.sleep_ms(900) -wdt.feed() -print(wdt) -time.sleep_ms(950) diff --git a/tests/wipy/wdt.py.exp b/tests/wipy/wdt.py.exp deleted file mode 100644 index 71f5e13b5361a..0000000000000 --- a/tests/wipy/wdt.py.exp +++ /dev/null @@ -1,7 +0,0 @@ -Exception -Exception -Exception - -Exception - - diff --git a/tests/wipy/wlan/machine.py b/tests/wipy/wlan/machine.py deleted file mode 100644 index 2ee5299651498..0000000000000 --- a/tests/wipy/wlan/machine.py +++ /dev/null @@ -1,42 +0,0 @@ -''' -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!') - -wifi = WLAN() - -print(machine) -machine.idle() -print(machine.freq() == (80000000,)) -print(machine.unique_id() == wifi.mac()) - -machine.main('main.py') - -rand_nums = [] -for i in range(0, 100): - rand = machine.rng() - if rand not in rand_nums: - rand_nums.append(rand) - else: - print('RNG number repeated') - break - -for i in range(0, 10): - machine.idle() - -print("Active") - -print(machine.reset_cause() >= 0) -print(machine.wake_reason() >= 0) - -try: - machine.main(123456) -except: - print('Exception') diff --git a/tests/wipy/wlan/machine.py.exp b/tests/wipy/wlan/machine.py.exp deleted file mode 100644 index cc5b3f61dab03..0000000000000 --- a/tests/wipy/wlan/machine.py.exp +++ /dev/null @@ -1,7 +0,0 @@ - -True -True -Active -True -True -Exception diff --git a/tests/wipy/wlan/server.py b/tests/wipy/wlan/server.py deleted file mode 100644 index 05847e376126c..0000000000000 --- a/tests/wipy/wlan/server.py +++ /dev/null @@ -1,41 +0,0 @@ -''' -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!') - -server = network.Server() - -print(server.timeout() == 300) -print(server.isrunning() == True) -server.deinit() -print(server.isrunning() == False) - -server.init(login=('test-user', 'test-password'), timeout=60) -print(server.isrunning() == True) -print(server.timeout() == 60) - -server.deinit() -print(server.isrunning() == False) -server.init() -print(server.isrunning() == True) - -try: - server.init(1) -except: - print('Exception') - -try: - server.init(0, login=('0000000000011111111111222222222222333333', 'abc')) -except: - print('Exception') - -try: - server.timeout(1) -except: - print('Exception') diff --git a/tests/wipy/wlan/server.py.exp b/tests/wipy/wlan/server.py.exp deleted file mode 100644 index a125ec934d9cd..0000000000000 --- a/tests/wipy/wlan/server.py.exp +++ /dev/null @@ -1,10 +0,0 @@ -True -True -True -True -True -True -True -Exception -Exception -Exception diff --git a/tests/wipy/wlan/wlan.py b/tests/wipy/wlan/wlan.py deleted file mode 100644 index 96121325cfb9d..0000000000000 --- a/tests/wipy/wlan/wlan.py +++ /dev/null @@ -1,181 +0,0 @@ -''' -WLAN test for the CC3200 based boards. -''' - -from network import WLAN -import os -import time -import testconfig - -mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') - - -def wait_for_connection(wifi, timeout=10): - while not wifi.isconnected() and timeout > 0: - time.sleep(1) - timeout -= 1 - if wifi.isconnected(): - print('Connected') - else: - print('Connection failed!') - - -wifi = WLAN(0, WLAN.STA) -print(wifi.mode() == WLAN.STA) -print(wifi.antenna() == WLAN.INT_ANT) - -wifi = WLAN(mode=WLAN.AP) -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) -print(wifi.mode() == WLAN.AP) -print(wifi.channel() == 7) -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 -scan_r = wifi.scan() -print(len(scan_r) > 3) -for net in scan_r: - if net.ssid == testconfig.wlan_ssid: - # test that the scan results contains the desired params - print(len(net.bssid) == 6) - print(net.channel == None) - print(net.sec == testconfig.wlan_auth[0]) - print(net.rssi < 0) - 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.auth(None) -print(wifi.auth() == None) -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 -scan_r = wifi.scan() -print(len(scan_r) > 3) -for net in scan_r: - if net.ssid == testconfig.wlan_ssid: - print('Network found') - break - -wifi.antenna(WLAN.INT_ANT) -wifi.mode(WLAN.STA) -print(wifi.mode() == WLAN.STA) -wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=10000) -wait_for_connection(wifi) - -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')) -wait_for_connection(wifi) -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) -wifi.disconnect() -print(wifi.isconnected() == False) - -t0 = time.ticks_ms() -wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=0) -print(time.ticks_ms() - t0 < 500) - -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) -print(wifi.mode() == WLAN.AP) - -# get the current instance without re-init -wifi = WLAN() -print(wifi.mode() == WLAN.AP) -wifi = WLAN(0) -print(wifi.mode() == WLAN.AP) - -# test the MAC address length -print(len(wifi.mac()) == 6) - -# next ones MUST raise -try: - wifi.init(mode=12345) -except: - print('Exception') - -try: - wifi.init(1, mode=WLAN.AP) -except: - print('Exception') - -try: - wifi.init(mode=WLAN.AP, ssid=None) -except: - print('Exception') - -try: - wifi = WLAN(mode=WLAN.AP, channel=12) -except: - print('Exception') - -try: - wifi.antenna(2) -except: - print('Exception') - -try: - wifi.mode(10) -except: - print('Exception') - -try: - wifi.ssid('11111sdfasdfasdfasdf564sdf654asdfasdf123451245ssdgfsdf1111111111111111111111111234123412341234asdfasdf') -except: - print('Exception') - -try: - wifi.auth((0)) -except: - print('Exception') - -try: - wifi.auth((0, None)) -except: - print('Exception') - -try: - wifi.auth((10, 10)) -except: - print('Exception') - -try: - wifi.channel(0) -except: - print('Exception') - -try: - wifi.ifconfig(1, 'dhcp') -except: - print('Exception') - -try: - wifi.ifconfig(config=()) -except: - print('Exception') diff --git a/tests/wipy/wlan/wlan.py.exp b/tests/wipy/wlan/wlan.py.exp deleted file mode 100644 index 2bb3537a225dc..0000000000000 --- a/tests/wipy/wlan/wlan.py.exp +++ /dev/null @@ -1,55 +0,0 @@ -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -True -Network found -True -True -True -True -True -True -True -True -Network found -True -Connected -Connected -True -Connected -True -Connected -True -True -True -True -True -True -True -True -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception -Exception diff --git a/tools/analyze_heap_dump.py b/tools/analyze_heap_dump.py index 887871db7afdd..d9b3dda599666 100755 --- a/tools/analyze_heap_dump.py +++ b/tools/analyze_heap_dump.py @@ -38,42 +38,73 @@ 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 add_symbol(name, address=None, size=None): 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 add_symbol(name, address=None, size=None): 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 add_symbol(name, address=None, size=None): # 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 load(address, size=4): 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 save_allocated_block(end, current_allocation): 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 save_allocated_block(end, current_allocation): 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 save_allocated_block(end, current_allocation): 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 save_allocated_block(end, current_allocation): if k == 0: potential_type = dynamic_type - if potential_type == dynamic_type: if k == 0: node.attr["fillcolor"] = "plum" @@ -341,7 +421,6 @@ def save_allocated_block(end, current_allocation): 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 save_allocated_block(end, current_allocation): 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 save_allocated_block(end, current_allocation): # 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 find_qstr(qstr_index): 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 find_qstr(qstr_index): 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 format(obj): 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 format(obj): 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 format(obj): 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 format(obj): 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 format(obj): 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 format(obj): 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) - - - 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") + 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.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 99c06f62ad631..8c2056e03019f 100755 --- a/tools/analyze_mpy.py +++ b/tools/analyze_mpy.py @@ -10,219 +10,129 @@ 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 @@ def _load_bytecode_qstrs(self, encoded_raw_code, bytecode): 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 70d5e2bc7a151..66ca48a02df80 100644 --- a/tools/build_board_info.py +++ b/tools/build_board_info.py @@ -19,16 +19,8 @@ sys.path.append("adabot") import adabot.github_requests as github -SUPPORTED_PORTS = [ - "atmel-samd", - "cxd56", - "esp32s2", - "litex", - "mimxrt10xx", - "nrf", - "raspberrypi", - "stm", -] +from shared_bindings_matrix import SUPPORTED_PORTS +from shared_bindings_matrix import aliases_by_board BIN = ("bin",) UF2 = ("uf2",) @@ -73,24 +65,33 @@ "meowbit_v121": UF2, } -aliases_by_board = { - "circuitplayground_express": [ - "circuitplayground_express_4h", - "circuitplayground_express_digikey_pycon2019", - ], - "pybadge": ["edgebadge"], - "pyportal": ["pyportal_pynt"], - "gemma_m0": ["gemma_m0_pycon2018"], - "pewpew10": ["pewpew13"], -} - - -def get_languages(): - languages = [] +language_allow_list = set([ + "ID", + "de_DE", + "en_GB", + "en_US", + "en_x_pirate", + "es", + "fil", + "fr", + "it_IT", + "ja", + "nl", + "pl", + "pt_BR", + "sv", + "zh_Latn_pinyin", +]) + + +def get_languages(list_all = False): + languages = set() for f in os.scandir("../locale"): if f.name.endswith(".po"): - languages.append(f.name[:-3]) - return languages + languages.add(f.name[:-3]) + if not list_all: + languages = languages & language_allow_list + return sorted(list(languages), key=str.casefold) def get_board_mapping(): @@ -125,9 +126,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 @@ -165,10 +164,7 @@ def get_current_info(): return git_info, current_info -def create_pr(changes, updated, git_info, user): - commit_sha, original_blob_sha = git_info - branch_name = "new_release_" + changes["new_release"] - +def create_json(updated): # Convert the dictionary to a list of boards. Liquid templates only handle arrays. updated_list = [] all_ids = sorted(updated.keys()) @@ -176,9 +172,15 @@ def create_pr(changes, updated, git_info, user): info = updated[id] info["id"] = id updated_list.append(info) + return json.dumps(updated_list, sort_keys=True, indent=1).encode("utf-8") + b"\n" - updated = json.dumps(updated_list, sort_keys=True, indent=1).encode("utf-8") + b"\n" + +def create_pr(changes, updated, git_info, user): + commit_sha, original_blob_sha = git_info + branch_name = "new_release_" + changes["new_release"] + updated = create_json(updated) # print(updated.decode("utf-8")) + pr_title = "Automated website update for release {}".format(changes["new_release"]) boards = "" if changes["new_boards"]: @@ -191,9 +193,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 +207,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 +256,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 @@ -269,7 +266,7 @@ def generate_download_info(): # Delete the release we are replacing for board in current_info: info = current_info[board] - for version in info["versions"]: + for version in list(info["versions"]): previous_releases.add(version["version"]) previous_languages.update(version["languages"]) if version["stable"] == new_stable or ( @@ -296,7 +293,7 @@ def generate_download_info(): new_version = { "stable": new_stable, "version": new_tag, - "modules": support_matrix.get(alias, "[]"), + "modules": support_matrix[alias], "languages": languages, "extensions": board_info["extensions"], } @@ -309,6 +306,8 @@ def generate_download_info(): create_pr(changes, current_info, git_info, user) else: print("No new release to update") + if "DEBUG" in os.environ: + print(create_json(current_info).decode("utf8")) if __name__ == "__main__": diff --git a/tools/build_memory_info.py b/tools/build_memory_info.py index 89aedf0f40581..722c548a1c281 100644 --- a/tools/build_memory_info.py +++ b/tools/build_memory_info.py @@ -9,11 +9,11 @@ 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 @@ 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 98e81499ed6fe..68aa45f0a00fb 100755 --- a/tools/build_release_files.py +++ b/tools/build_release_files.py @@ -17,7 +17,7 @@ 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,9 +27,14 @@ sha, version = build_info.get_version_info() languages = build_info.get_languages() + +all_languages = build_info.get_languages(list_all=True) + +print("Note: Not building languages", set(all_languages) - set(languages)) + 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) @@ -45,8 +50,12 @@ # 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) @@ -55,8 +64,16 @@ 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" @@ -68,13 +85,14 @@ 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) @@ -83,9 +101,15 @@ 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 f75269130fb2e..2328edd72ff04 100644 --- a/tools/chart_code_size.py +++ b/tools/chart_code_size.py @@ -12,15 +12,15 @@ # 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 get_size(t): 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 get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): else: print(line) else: - #print(line) + # print(line) pass # print() @@ -344,7 +368,7 @@ def get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): # 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 get_pointer_map(t, depth=0): 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 get_pointer_map(t, depth=0): 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 cb4efc5f11366..33260eb39064e 100644 --- a/tools/ci_check_duplicate_usb_vid_pid.py +++ b/tools/ci_check_duplicate_usb_vid_pid.py @@ -46,7 +46,7 @@ "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 @@ "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. + """A pathlib glob search for all ports/*/boards/*/mpconfigboard.mk file + paths. - :returns: A ``pathlib.Path.glob()`` genarator object + :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 @@ def check_vid_pid(files, ignorelist): 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 86010bad3e726..3b41c8d67b45c 100644 --- a/tools/ci_new_boards_check.py +++ b/tools/ci_new_boards_check.py @@ -11,17 +11,19 @@ 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 @@ 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 @@ 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 new file mode 100644 index 0000000000000..58c5a8e39f7bf --- /dev/null +++ b/tools/codeformat.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +# +# This file is part of the MicroPython project, http://micropython.org/ +# +# The MIT License (MIT) +# +# Copyright (c) 2020 Damien P. George +# Copyright (c) 2020 Jim Mussared +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import argparse +import glob +import fnmatch +import itertools +import os +import pathlib +import re +import subprocess + +# Relative to top-level repo dir. +PATHS = [ + # C + "devices/**/*.[ch]", + "drivers/bus/*.[ch]", + "extmod/*.[ch]", + "lib/netutils/*.[ch]", + "lib/timeutils/*.[ch]", + "lib/utils/*.[ch]", + "mpy-cross/**/*.[ch]", + "ports/**/*.[ch]", + "py/**/*.[ch]", + "shared-bindings/**/*.[ch]", + "shared-module/**/*.[ch]", + "supervisor/**/*.[ch]", + # Python + "extmod/*.py", + "ports/**/*.py", + "py/**/*.py", + "tools/**/*.py", + "tests/**/*.py", +] + +EXCLUSIONS = [ + # STM32 build includes generated Python code. + "ports/*/build*", + # gitignore in ports/unix ignores *.py, so also do it here. + "ports/unix/*.py", + # not real python files + "tests/**/repl_*.py", + # needs careful attention before applying automatic formatting + "tests/basics/*.py", +] + +# Path to repo top-level dir. +TOP = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + +UNCRUSTIFY_CFG = os.path.join(TOP, "tools/uncrustify.cfg") + +C_EXTS = (".c", ".h") +PY_EXTS = (".py",) + + +def list_files(args, paths, exclusions=None, prefix=""): + files = set() + args = [os.path.join(prefix, arg) for arg in args] + for pattern in paths: + files.update(arg for arg in args if pathlib.Path(arg).match(pattern)) + for pattern in exclusions or []: + files.difference_update(fnmatch.filter(files, os.path.join(prefix, pattern))) + return sorted(files) + + +def fixup_c(filename): + # Read file. + with open(filename) as f: + lines = f.readlines() + + # Write out file with fixups. + with open(filename, "w", newline="") as f: + dedent_stack = [] + while lines: + # Get next line. + l = lines.pop(0) + + # Revert "// |" back to "//| " + if l.startswith("// |"): + l = "//|" + l[4:] + + # Dedent #'s to match indent of following line (not previous line). + m = re.match(r"( +)#(if |ifdef |ifndef |elif |else|endif)", l) + if m: + indent = len(m.group(1)) + directive = m.group(2) + if directive in ("if ", "ifdef ", "ifndef "): + l_next = lines[0] + indent_next = len(re.match(r"( *)", l_next).group(1)) + if indent - 4 == indent_next and re.match(r" +(} else |case )", l_next): + # This #-line (and all associated ones) needs dedenting by 4 spaces. + l = l[4:] + dedent_stack.append(indent - 4) + else: + # This #-line does not need dedenting. + dedent_stack.append(-1) + else: + if dedent_stack: + if dedent_stack[-1] >= 0: + # This associated #-line needs dedenting to match the #if. + indent_diff = indent - dedent_stack[-1] + assert indent_diff >= 0 + l = l[indent_diff:] + if directive == "endif": + dedent_stack.pop() + + # Write out line. + f.write(l) + + assert not dedent_stack, filename + + +def main(): + cmd_parser = argparse.ArgumentParser(description="Auto-format C and Python files -- to be used via pre-commit only.") + cmd_parser.add_argument("-c", action="store_true", help="Format C code only") + cmd_parser.add_argument("-p", action="store_true", help="Format Python code only") + cmd_parser.add_argument("-v", action="store_true", help="Enable verbose output") + cmd_parser.add_argument("files", nargs="+", help="Run on specific globs") + args = cmd_parser.parse_args() + + # Setting only one of -c or -p disables the other. If both or neither are set, then do both. + format_c = args.c or not args.p + format_py = args.p or not args.c + + # Expand the arguments passed on the command line, subject to the PATHS and EXCLUSIONS + files = list_files(args.files, PATHS, EXCLUSIONS, TOP) + + # Extract files matching a specific language. + def lang_files(exts): + for file in files: + if os.path.splitext(file)[1].lower() in exts: + yield file + + # Run tool on N files at a time (to avoid making the command line too long). + def batch(cmd, files, N=200): + while True: + file_args = list(itertools.islice(files, N)) + if not file_args: + break + subprocess.call(cmd + file_args) + + # Format C files with uncrustify. + if format_c: + command = ["uncrustify", "-c", UNCRUSTIFY_CFG, "-lC", "--no-backup"] + if not args.v: + command.append("-q") + batch(command, lang_files(C_EXTS)) + for file in lang_files(C_EXTS): + fixup_c(file) + + # Format Python files with black. + if format_py: + command = ["black", "--fast", "--line-length=99"] + if args.v: + command.append("-v") + else: + command.append("-q") + batch(command, lang_files(PY_EXTS)) + + +if __name__ == "__main__": + main() diff --git a/tools/convert_release_notes.py b/tools/convert_release_notes.py index 797e71834b88a..964a7fc3767e8 100644 --- a/tools/convert_release_notes.py +++ b/tools/convert_release_notes.py @@ -16,13 +16,14 @@ 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 @@ def emphasis(self, text): 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 464be4ba44ce9..647a3ddc5ac18 100644 --- a/tools/cpboard.py +++ b/tools/cpboard.py @@ -100,9 +100,7 @@ def reset(self): # 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 @@ def __init__(self, dev): 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 @@ def from_try_all(cls, name, **kwargs): 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 @@ def __init__(self, device, baudrate=115200, wait=0, timeout=10): 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 @@ def _reset(self, mode="NORMAL"): % 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 @@ def get_disks(self): 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 @@ def execfile(self, filename, timeout=10): 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 489465f0cff1a..4dcb4fdca7a75 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 - -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)) - - # 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 706dd4dd23cdf..df9cc02fdabba 100644 --- a/tools/file2h.py +++ b/tools/file2h.py @@ -16,19 +16,19 @@ # 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 0362923e885f4..4c6f89b26fff7 100644 --- a/tools/fixup_translations.py +++ b/tools/fixup_translations.py @@ -45,7 +45,9 @@ 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 @@ 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 @@ 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 cc9a218361663..6a1772faa7cab 100644 --- a/tools/gc_activity.py +++ b/tools/gc_activity.py @@ -10,18 +10,22 @@ 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 f906cf5c7e4c2..f1afede702323 100644 --- a/tools/gc_activity_between_collects.py +++ b/tools/gc_activity_between_collects.py @@ -10,18 +10,22 @@ 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 @@ def change_root(trace, size): 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 6657b6a272d7f..69ad501787e50 100644 --- a/tools/gen_display_resources.py +++ b/tools/gen_display_resources.py @@ -8,30 +8,33 @@ import struct import sys -sys.path.append("bitmap_font") -sys.path.append("../../tools/bitmap_font") +sys.path.insert(0, "bitmap_font") +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 @@ def _load_row(self, y, row): 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 @@ def _load_row(self, y, row): 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 @@ def _load_row(self, y, row): 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 @@ def _load_row(self, y, row): .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 @@ def _load_row(self, y, row): .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 @@ def _load_row(self, y, row): .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 @@ def _load_row(self, y, row): .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 @@ def _load_row(self, y, row): .cursor_y = 0, .tilegrid = &supervisor_terminal_text_grid }; -""") +""" +) diff --git a/tools/gen_ld_files.py b/tools/gen_ld_files.py index 1fea1a7efa11d..28f73d9be29e9 100755 --- a/tools/gen_ld_files.py +++ b/tools/gen_ld_files.py @@ -12,31 +12,39 @@ 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 @@ def remove_UL(s): 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_nvm_devices.py b/tools/gen_nvm_devices.py new file mode 100644 index 0000000000000..3cda8671fdcc6 --- /dev/null +++ b/tools/gen_nvm_devices.py @@ -0,0 +1,23 @@ +import sys +import cascadetoml +import pathlib +import typer +from jinja2 import Template + + +def main(input_template: pathlib.Path, output_path: pathlib.Path): + flashes = cascadetoml.filter_toml(pathlib.Path("../../data/nvm.toml"), []) + + template = Template(input_template.read_text()) + + settings = {"nvms": []} + for flash in flashes["nvm"]: + if "sku" not in flash or flash["sku"] == flash["manufacturer"]: + continue + settings["nvms"].append(dict(flash)) + + output_path.write_text(template.render(settings)) + + +if __name__ == "__main__": + typer.run(main) diff --git a/tools/gen_usb_descriptor.py b/tools/gen_usb_descriptor.py index 672f09c889485..1fad2fbeb32fe 100644 --- a/tools/gen_usb_descriptor.py +++ b/tools/gen_usb_descriptor.py @@ -12,60 +12,102 @@ from adafruit_usb_descriptor import audio, audio10, cdc, hid, midi, msc, standard, util import hid_report_descriptors -DEFAULT_INTERFACE_NAME = 'CircuitPython' -ALL_DEVICES='CDC,MSC,AUDIO,HID' -ALL_DEVICES_SET=frozenset(ALL_DEVICES.split(',')) -DEFAULT_DEVICES='CDC,MSC,AUDIO,HID' - -ALL_HID_DEVICES='KEYBOARD,MOUSE,CONSUMER,SYS_CONTROL,GAMEPAD,DIGITIZER,XAC_COMPATIBLE_GAMEPAD,RAW' -ALL_HID_DEVICES_SET=frozenset(ALL_HID_DEVICES.split(',')) +DEFAULT_INTERFACE_NAME = "CircuitPython" +ALL_DEVICES = "CDC CDC2 MSC AUDIO HID VENDOR" +ALL_DEVICES_SET = frozenset(ALL_DEVICES.split()) +DEFAULT_DEVICES = "CDC MSC AUDIO HID" + +# This list is in preferred order. MacOS does not like GAMEPAD coming before MOUSE. +ALL_HID_DEVICES = ( + "KEYBOARD MOUSE CONSUMER SYS_CONTROL GAMEPAD DIGITIZER XAC_COMPATIBLE_GAMEPAD RAW" +) +ALL_HID_DEVICES_ORDER = dict((name, idx) for (idx, name) in enumerate(ALL_HID_DEVICES.split())) +ALL_HID_DEVICES_SET = frozenset(ALL_HID_DEVICES.split()) # Digitizer works on Linux but conflicts with mouse, so omit it. -DEFAULT_HID_DEVICES='KEYBOARD,MOUSE,CONSUMER,GAMEPAD' - -parser = argparse.ArgumentParser(description='Generate USB descriptors.') -parser.add_argument('--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') -parser.add_argument('--vid', type=lambda x: int(x, 16), - help='vendor id') -parser.add_argument('--pid', type=lambda x: int(x, 16), - help='product id') -parser.add_argument('--serial_number_length', type=int, default=32, - help='length needed for the serial number in digits') -parser.add_argument('--devices', type=lambda l: tuple(l.split(',')), default=DEFAULT_DEVICES, - help='devices to include in descriptor (AUDIO includes MIDI support)') -parser.add_argument('--hid_devices', type=lambda l: tuple(l.split(',')), default=DEFAULT_HID_DEVICES, - help='HID devices to include in HID report descriptor') -parser.add_argument('--interface_name', type=str, - help='The name/prefix to use in the interface descriptions', - default=DEFAULT_INTERFACE_NAME) -parser.add_argument('--no-renumber_endpoints', dest='renumber_endpoints', action='store_false', - help='use to not renumber endpoint') -parser.add_argument('--cdc_ep_num_notification', type=int, default=0, - help='endpoint number of CDC NOTIFICATION') -parser.add_argument('--cdc_ep_num_data_out', type=int, default=0, - help='endpoint number of CDC DATA OUT') -parser.add_argument('--cdc_ep_num_data_in', type=int, default=0, - help='endpoint number of CDC 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('--output_c_file', type=argparse.FileType('w', encoding='UTF-8'), required=True) -parser.add_argument('--output_h_file', type=argparse.FileType('w', encoding='UTF-8'), required=True) +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 + +parser = argparse.ArgumentParser(description="Generate USB descriptors.") +parser.add_argument( + "--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") +parser.add_argument("--vid", type=lambda x: int(x, 16), help="vendor id") +parser.add_argument("--pid", type=lambda x: int(x, 16), help="product id") +parser.add_argument( + "--serial_number_length", + type=int, + default=32, + help="length needed for the serial number in digits", +) +parser.add_argument( + "--devices", + type=lambda l: tuple(l.split()), + default=DEFAULT_DEVICES, + help="devices to include in descriptor (AUDIO includes MIDI support)", +) +parser.add_argument( + "--hid_devices", + type=lambda l: tuple(l.split()), + default=DEFAULT_HID_DEVICES, + help="HID devices to include in HID report descriptor", +) +parser.add_argument( + "--interface_name", + type=str, + help="The name/prefix to use in the interface descriptions", + default=DEFAULT_INTERFACE_NAME, +) +parser.add_argument( + "--no-renumber_endpoints", + dest="renumber_endpoints", + action="store_false", + help="use to not renumber endpoint", +) +parser.add_argument( + "--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" +) +parser.add_argument( + "--cdc_ep_num_data_out", type=int, default=0, help="endpoint number of CDC DATA OUT" +) +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" +) +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( + "--webusb_url", + type=str, + help="The URL to include in the WebUSB URL Descriptor", + default=DEFAULT_WEBUSB_URL, +) +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( + "--output_c_file", type=argparse.FileType("w", encoding="UTF-8"), required=True +) +parser.add_argument( + "--output_h_file", type=argparse.FileType("w", encoding="UTF-8"), required=True +) args = parser.parse_args() @@ -77,41 +119,67 @@ if unknown_hid_devices: raise ValueError("Unknown HID devices(s)", unknown_hid_devices) +include_cdc = "CDC" in args.devices +include_cdc2 = "CDC2" in args.devices +include_msc = "MSC" in args.devices +include_hid = "HID" in args.devices +include_audio = "AUDIO" in args.devices +include_vendor = "VENDOR" in args.devices + +if not include_cdc and include_cdc2: + raise ValueError("CDC2 requested without CDC") + if not args.renumber_endpoints: - if 'CDC' in args.devices: + if include_cdc: if args.cdc_ep_num_notification == 0: raise ValueError("CDC notification endpoint number must not be 0") - elif args.cdc_ep_num_data_out == 0: + if args.cdc_ep_num_data_out == 0: raise ValueError("CDC data OUT endpoint number must not be 0") - elif args.cdc_ep_num_data_in == 0: + if args.cdc_ep_num_data_in == 0: raise ValueError("CDC data IN endpoint number must not be 0") - if 'MSC' in args.devices: + if include_cdc2: + if args.cdc2_ep_num_notification == 0: + raise ValueError("CDC2 notification endpoint number must not be 0") + if args.cdc2_ep_num_data_out == 0: + raise ValueError("CDC2 data OUT endpoint number must not be 0") + if args.cdc2_ep_num_data_in == 0: + raise ValueError("CDC2 data IN endpoint number must not be 0") + + if include_msc: if args.msc_ep_num_out == 0: raise ValueError("MSC endpoint OUT number must not be 0") - elif args.msc_ep_num_in == 0: + if args.msc_ep_num_in == 0: raise ValueError("MSC endpoint IN number must not be 0") - if 'HID' in args.devices: + if include_hid: if args.args.hid_ep_num_out == 0: raise ValueError("HID endpoint OUT number must not be 0") - elif args.hid_ep_num_in == 0: + if args.hid_ep_num_in == 0: raise ValueError("HID endpoint IN number must not be 0") - if 'AUDIO' in args.devices: + if include_audio: if args.args.midi_ep_num_out == 0: raise ValueError("MIDI endpoint OUT number must not be 0") - elif args.midi_ep_num_in == 0: + if args.midi_ep_num_in == 0: raise ValueError("MIDI endpoint IN number must not be 0") + if include_vendor: + if args.vendor_ep_num_out == 0: + raise ValueError("VENDOR endpoint OUT number must not be 0") + if args.vendor_ep_num_in == 0: + raise ValueError("VENDOR endpoint IN number must not be 0") + + class StringIndex: """Assign a monotonically increasing index to each unique string. Start with 0.""" + string_to_index = {} index_to_variable = {} strings = [] @classmethod - def index(cls, string, *, variable_name = None): + def index(cls, string, *, variable_name=None): if string in cls.string_to_index: idx = cls.string_to_index[string] if not cls.index_to_variable[idx]: @@ -129,11 +197,12 @@ def strings_in_order(cls): return cls.strings - # langid must be the 0th string descriptor LANGID_INDEX = StringIndex.index("\u0409", variable_name="language_id") assert LANGID_INDEX == 0 -SERIAL_NUMBER_INDEX = StringIndex.index("S" * args.serial_number_length, variable_name="usb_serial_number") +SERIAL_NUMBER_INDEX = StringIndex.index( + "S" * args.serial_number_length, variable_name="usb_serial_number" +) device = standard.DeviceDescriptor( description="top", @@ -141,238 +210,325 @@ def strings_in_order(cls): idProduct=args.pid, iManufacturer=StringIndex.index(args.manufacturer), iProduct=StringIndex.index(args.product), - iSerialNumber=SERIAL_NUMBER_INDEX) + iSerialNumber=SERIAL_NUMBER_INDEX, +) # Interface numbers are interface-set local and endpoints are interface local # until util.join_interfaces renumbers them. -cdc_union = cdc.Union( - description="CDC comm", - bMasterInterface=0x00, # Adjust this after interfaces are renumbered. - bSlaveInterface_list=[0x01]) # Adjust this after interfaces are renumbered. - -cdc_call_management = cdc.CallManagement( - description="CDC comm", - bmCapabilities=0x01, - bDataInterface=0x01) # Adjust this after interfaces are renumbered. - -cdc_comm_interface = standard.InterfaceDescriptor( - description="CDC comm", - bInterfaceClass=cdc.CDC_CLASS_COMM, # Communications Device Class - bInterfaceSubClass=cdc.CDC_SUBCLASS_ACM, # Abstract control model - bInterfaceProtocol=cdc.CDC_PROTOCOL_NONE, - iInterface=StringIndex.index("{} CDC control".format(args.interface_name)), - subdescriptors=[ - cdc.Header( - description="CDC comm", - bcdCDC=0x0110), - cdc_call_management, - cdc.AbstractControlManagement( - description="CDC comm", - bmCapabilities=0x02), - cdc_union, - standard.EndpointDescriptor( - description="CDC comm in", - bEndpointAddress=args.cdc_ep_num_notification | standard.EndpointDescriptor.DIRECTION_IN, - bmAttributes=standard.EndpointDescriptor.TYPE_INTERRUPT, - wMaxPacketSize=0x0040, - bInterval=0x10) - ]) - -cdc_data_interface = standard.InterfaceDescriptor( - description="CDC data", - bInterfaceClass=cdc.CDC_CLASS_DATA, - iInterface=StringIndex.index("{} CDC data".format(args.interface_name)), - subdescriptors=[ - standard.EndpointDescriptor( - description="CDC data out", - bEndpointAddress=args.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="CDC data in", - bEndpointAddress=args.cdc_ep_num_data_in | standard.EndpointDescriptor.DIRECTION_IN, - bmAttributes=standard.EndpointDescriptor.TYPE_BULK, - bInterval=0, - wMaxPacketSize=512 if args.highspeed else 64), - ]) - -cdc_interfaces = [cdc_comm_interface, cdc_data_interface] - -msc_interfaces = [ - standard.InterfaceDescriptor( - description="MSC", - bInterfaceClass=msc.MSC_CLASS, - bInterfaceSubClass=msc.MSC_SUBCLASS_TRANSPARENT, - bInterfaceProtocol=msc.MSC_PROTOCOL_BULK, - iInterface=StringIndex.index("{} Mass Storage".format(args.interface_name)), + +def make_cdc_union(name): + return cdc.Union( + description="{} comm".format(name), + # Set bMasterInterface and bSlaveInterface_list to proper values after interfaces are renumbered. + bMasterInterface=0x00, + bSlaveInterface_list=[0x01], + ) + + +def make_cdc_call_management(name): + # Set bDataInterface to proper value after interfaces are renumbered. + return cdc.CallManagement( + description="{} comm".format(name), bmCapabilities=0x01, bDataInterface=0x01 + ) + + +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 + bInterfaceSubClass=cdc.CDC_SUBCLASS_ACM, # Abstract control model + bInterfaceProtocol=cdc.CDC_PROTOCOL_NONE, + iInterface=StringIndex.index("{} {} control".format(args.interface_name, name)), subdescriptors=[ + cdc.Header(description="{} comm".format(name), bcdCDC=0x0110), + cdc_call_management, + cdc.AbstractControlManagement(description="{} comm".format(name), bmCapabilities=0x02), + cdc_union, standard.EndpointDescriptor( - description="MSC in", - bEndpointAddress=args.msc_ep_num_in | standard.EndpointDescriptor.DIRECTION_IN, + description="{} comm in".format(name), + bEndpointAddress=cdc_ep_num_notification + | standard.EndpointDescriptor.DIRECTION_IN, + bmAttributes=standard.EndpointDescriptor.TYPE_INTERRUPT, + wMaxPacketSize=0x0040, + bInterval=0x10, + ), + ], + ) + + +def make_cdc_data_interface(name, cdc_ep_num_data_in, cdc_ep_num_data_out): + return standard.InterfaceDescriptor( + description="{} data".format(name), + bInterfaceClass=cdc.CDC_CLASS_DATA, + iInterface=StringIndex.index("{} {} data".format(args.interface_name, name)), + subdescriptors=[ + standard.EndpointDescriptor( + description="{} data out".format(name), + bEndpointAddress=cdc_ep_num_data_out | standard.EndpointDescriptor.DIRECTION_OUT, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=0, - wMaxPacketSize=512 if args.highspeed else 64), + wMaxPacketSize=512 if args.highspeed else 64, + ), standard.EndpointDescriptor( - description="MSC out", - bEndpointAddress=(args.msc_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT), + description="{} data in".format(name), + bEndpointAddress=cdc_ep_num_data_in | standard.EndpointDescriptor.DIRECTION_IN, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=0, - wMaxPacketSize=512 if args.highspeed else 64), - ] + wMaxPacketSize=512 if args.highspeed else 64, + ), + ], ) -] -# When there's only one hid_device, it shouldn't have a report id. -# Otherwise, report ids are assigned sequentially: -# args.hid_devices[0] has report_id 1 -# args.hid_devices[1] has report_id 2 -# etc. -report_ids = {} +if include_cdc: + cdc_union = make_cdc_union("CDC") + cdc_call_management = make_cdc_call_management("CDC") + cdc_comm_interface = make_cdc_comm_interface( + "CDC", cdc_union, cdc_call_management, args.cdc_ep_num_notification + ) + cdc_data_interface = make_cdc_data_interface( + "CDC", args.cdc_ep_num_data_in, args.cdc_ep_num_data_out + ) -if len(args.hid_devices) == 1: - 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_ids[name] = 0 -else: - report_id = 1 - concatenated_descriptors = bytearray() - for name in args.hid_devices: - concatenated_descriptors.extend( - bytes(hid_report_descriptors.REPORT_DESCRIPTOR_FUNCTIONS[name](report_id))) - report_ids[name] = report_id - report_id += 1 - combined_hid_report_descriptor = hid.ReportDescriptor( - description="MULTIDEVICE", - report_descriptor=bytes(concatenated_descriptors)) - -# ASF4 expects keyboard and generic devices to have both in and out endpoints, -# and will fail (possibly silently) if both are not supplied. -hid_endpoint_in_descriptor = standard.EndpointDescriptor( - description="HID in", - bEndpointAddress=args.hid_ep_num_in | standard.EndpointDescriptor.DIRECTION_IN, - bmAttributes=standard.EndpointDescriptor.TYPE_INTERRUPT, - bInterval=8) - -hid_endpoint_out_descriptor = standard.EndpointDescriptor( - description="HID out", - bEndpointAddress=args.hid_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT, - bmAttributes=standard.EndpointDescriptor.TYPE_INTERRUPT, - bInterval=8) - -hid_interfaces = [ - standard.InterfaceDescriptor( - description="HID Multiple Devices", - bInterfaceClass=hid.HID_CLASS, - bInterfaceSubClass=hid.HID_SUBCLASS_NOBOOT, - bInterfaceProtocol=hid.HID_PROTOCOL_NONE, - iInterface=StringIndex.index("{} HID".format(args.interface_name)), - subdescriptors=[ - hid.HIDDescriptor( - description="HID", - wDescriptorLength=len(bytes(combined_hid_report_descriptor))), - hid_endpoint_in_descriptor, - hid_endpoint_out_descriptor, - ] - ), + cdc_interfaces = [cdc_comm_interface, cdc_data_interface] + +if include_cdc2: + cdc2_union = make_cdc_union("CDC2") + cdc2_call_management = make_cdc_call_management("CDC2") + cdc2_comm_interface = make_cdc_comm_interface( + "CDC2", cdc2_union, cdc2_call_management, args.cdc2_ep_num_notification + ) + cdc2_data_interface = make_cdc_data_interface( + "CDC2", args.cdc2_ep_num_data_in, args.cdc2_ep_num_data_out + ) + + cdc2_interfaces = [cdc2_comm_interface, cdc2_data_interface] + +if include_msc: + msc_interfaces = [ + standard.InterfaceDescriptor( + description="MSC", + bInterfaceClass=msc.MSC_CLASS, + bInterfaceSubClass=msc.MSC_SUBCLASS_TRANSPARENT, + bInterfaceProtocol=msc.MSC_PROTOCOL_BULK, + iInterface=StringIndex.index("{} Mass Storage".format(args.interface_name)), + subdescriptors=[ + standard.EndpointDescriptor( + description="MSC 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, + ), + standard.EndpointDescriptor( + description="MSC out", + bEndpointAddress=( + args.msc_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT + ), + bmAttributes=standard.EndpointDescriptor.TYPE_BULK, + bInterval=0, + wMaxPacketSize=512 if args.highspeed else 64, + ), + ], + ) ] -# Audio! -# In and out here are relative to CircuitPython - -# USB OUT -> midi_in_jack_emb -> midi_out_jack_ext -> CircuitPython -midi_in_jack_emb = midi.InJackDescriptor( - description="MIDI PC -> {}".format(args.interface_name), - bJackType=midi.JACK_TYPE_EMBEDDED, - iJack=StringIndex.index("{} usb_midi.ports[0]".format(args.interface_name))) -midi_out_jack_ext = midi.OutJackDescriptor( - description="MIDI data out to user code.", - bJackType=midi.JACK_TYPE_EXTERNAL, - input_pins=[(midi_in_jack_emb, 1)], - iJack=0) - -# 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) -midi_out_jack_emb = midi.OutJackDescriptor( - description="MIDI PC <- {}".format(args.interface_name), - bJackType=midi.JACK_TYPE_EMBEDDED, - input_pins=[(midi_in_jack_ext, 1)], - iJack=StringIndex.index("{} usb_midi.ports[1]".format(args.interface_name))) - - -audio_midi_interface = standard.InterfaceDescriptor( - description="Midi goodness", - bInterfaceClass=audio.AUDIO_CLASS_DEVICE, - bInterfaceSubClass=audio.AUDIO_SUBCLASS_MIDI_STREAMING, - bInterfaceProtocol=audio.AUDIO_PROTOCOL_V1, - iInterface=StringIndex.index("{} MIDI".format(args.interface_name)), - subdescriptors=[ - midi.Header( - jacks_and_elements=[ - midi_in_jack_emb, - midi_in_jack_ext, - midi_out_jack_emb, - midi_out_jack_ext + +if include_hid: + # When there's only one hid_device, it shouldn't have a report id. + # Otherwise, report ids are assigned sequentially: + # args.hid_devices[0] has report_id 1 + # args.hid_devices[1] has report_id 2 + # etc. + + report_ids = {} + + if len(args.hid_devices) == 1: + 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_ids[name] = 0 + else: + report_id = 1 + concatenated_descriptors = bytearray() + # Sort HID devices by preferred order. + for name in sorted(args.hid_devices, key=ALL_HID_DEVICES_ORDER.get): + concatenated_descriptors.extend( + bytes(hid_report_descriptors.REPORT_DESCRIPTOR_FUNCTIONS[name](report_id)) + ) + report_ids[name] = report_id + report_id += 1 + combined_hid_report_descriptor = hid.ReportDescriptor( + description="MULTIDEVICE", report_descriptor=bytes(concatenated_descriptors) + ) + + # ASF4 expects keyboard and generic devices to have both in and out endpoints, + # and will fail (possibly silently) if both are not supplied. + hid_endpoint_in_descriptor = standard.EndpointDescriptor( + description="HID in", + bEndpointAddress=args.hid_ep_num_in | standard.EndpointDescriptor.DIRECTION_IN, + bmAttributes=standard.EndpointDescriptor.TYPE_INTERRUPT, + bInterval=8, + ) + + hid_endpoint_out_descriptor = standard.EndpointDescriptor( + description="HID out", + bEndpointAddress=args.hid_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT, + bmAttributes=standard.EndpointDescriptor.TYPE_INTERRUPT, + bInterval=8, + ) + + hid_interfaces = [ + standard.InterfaceDescriptor( + description="HID Multiple Devices", + bInterfaceClass=hid.HID_CLASS, + bInterfaceSubClass=hid.HID_SUBCLASS_NOBOOT, + bInterfaceProtocol=hid.HID_PROTOCOL_NONE, + iInterface=StringIndex.index("{} HID".format(args.interface_name)), + subdescriptors=[ + hid.HIDDescriptor( + description="HID", wDescriptorLength=len(bytes(combined_hid_report_descriptor)) + ), + hid_endpoint_in_descriptor, + hid_endpoint_out_descriptor, ], - ), - standard.EndpointDescriptor( - description="MIDI data out to {}".format(args.interface_name), - bEndpointAddress=args.midi_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT, - bmAttributes=standard.EndpointDescriptor.TYPE_BULK, - bInterval=0, - wMaxPacketSize=512 if args.highspeed else 64), - 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, - bmAttributes=standard.EndpointDescriptor.TYPE_BULK, - bInterval = 0x0, - wMaxPacketSize=512 if args.highspeed else 64), - midi.DataEndpointDescriptor(baAssocJack=[midi_out_jack_emb]), - ]) - -cs_ac_interface = audio10.AudioControlInterface( + ) + ] + +if include_audio: + # Audio! + # In and out here are relative to CircuitPython + + # USB OUT -> midi_in_jack_emb -> midi_out_jack_ext -> CircuitPython + midi_in_jack_emb = midi.InJackDescriptor( + description="MIDI PC -> {}".format(args.interface_name), + bJackType=midi.JACK_TYPE_EMBEDDED, + iJack=StringIndex.index("{} usb_midi.ports[0]".format(args.interface_name)), + ) + midi_out_jack_ext = midi.OutJackDescriptor( + description="MIDI data out to user code.", + bJackType=midi.JACK_TYPE_EXTERNAL, + input_pins=[(midi_in_jack_emb, 1)], + iJack=0, + ) + + # 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 + ) + midi_out_jack_emb = midi.OutJackDescriptor( + description="MIDI PC <- {}".format(args.interface_name), + bJackType=midi.JACK_TYPE_EMBEDDED, + input_pins=[(midi_in_jack_ext, 1)], + iJack=StringIndex.index("{} usb_midi.ports[1]".format(args.interface_name)), + ) + + audio_midi_interface = standard.InterfaceDescriptor( + description="Midi goodness", + bInterfaceClass=audio.AUDIO_CLASS_DEVICE, + bInterfaceSubClass=audio.AUDIO_SUBCLASS_MIDI_STREAMING, + bInterfaceProtocol=audio.AUDIO_PROTOCOL_V1, + iInterface=StringIndex.index("{} MIDI".format(args.interface_name)), + subdescriptors=[ + midi.Header( + jacks_and_elements=[ + midi_in_jack_emb, + 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, + bmAttributes=standard.EndpointDescriptor.TYPE_BULK, + bInterval=0, + wMaxPacketSize=512 if args.highspeed else 64, + ), + 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, + bmAttributes=standard.EndpointDescriptor.TYPE_BULK, + bInterval=0x0, + wMaxPacketSize=512 if args.highspeed else 64, + ), + midi.DataEndpointDescriptor(baAssocJack=[midi_out_jack_emb]), + ], + ) + + cs_ac_interface = audio10.AudioControlInterface( description="Empty audio control", - audio_streaming_interfaces = [], - midi_streaming_interfaces = [ - audio_midi_interface - ] + audio_streaming_interfaces=[], + midi_streaming_interfaces=[audio_midi_interface], ) -audio_control_interface = standard.InterfaceDescriptor( + audio_control_interface = standard.InterfaceDescriptor( description="All the audio", bInterfaceClass=audio.AUDIO_CLASS_DEVICE, 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. -audio_interfaces = [audio_control_interface] + cs_ac_interface.audio_streaming_interfaces + cs_ac_interface.midi_streaming_interfaces + # Audio streaming interfaces must occur before MIDI ones. + audio_interfaces = ( + [audio_control_interface] + + cs_ac_interface.audio_streaming_interfaces + + cs_ac_interface.midi_streaming_interfaces + ) + +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, + 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, + bmAttributes=standard.EndpointDescriptor.TYPE_BULK, + bInterval=16, + ) + + vendor_interface = standard.InterfaceDescriptor( + description="VENDOR", + bInterfaceClass=0xFF, # Vendor-specific + bInterfaceSubClass=0x00, + bInterfaceProtocol=0x00, + iInterface=StringIndex.index("{} VENDOR".format(args.interface_name)), + subdescriptors=[vendor_endpoint_in_descriptor, vendor_endpoint_out_descriptor], + ) + + vendor_interfaces = [vendor_interface] interfaces_to_join = [] -if 'CDC' in args.devices: +if include_cdc: interfaces_to_join.append(cdc_interfaces) -if 'MSC' in args.devices: +if include_cdc2: + interfaces_to_join.append(cdc2_interfaces) + +if include_msc: interfaces_to_join.append(msc_interfaces) -if 'HID' in args.devices: +if include_hid: interfaces_to_join.append(hid_interfaces) -if 'AUDIO' in args.devices: +if include_audio: interfaces_to_join.append(audio_interfaces) +if include_vendor: + interfaces_to_join.append(vendor_interfaces) + # 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. @@ -381,30 +537,49 @@ def strings_in_order(cls): if args.max_ep != 0: for interface in interfaces: for subdescriptor in interface.subdescriptors: - endpoint_address = getattr(subdescriptor, 'bEndpointAddress', 0) & 0x7f + endpoint_address = getattr(subdescriptor, "bEndpointAddress", 0) & 0x7F if endpoint_address >= args.max_ep: - raise ValueError("Endpoint address %d of %s must be less than %d" % (endpoint_address & 0x7f, interface.description, args.max_ep)) + raise ValueError( + "Endpoint address %d of '%s' must be less than %d; you have probably run out of endpoints" + % (endpoint_address & 0x7F, interface.description, args.max_ep) + ) else: print("Unable to check whether maximum number of endpoints is respected", file=sys.stderr) # Now adjust the CDC interface cross-references. -cdc_union.bMasterInterface = cdc_comm_interface.bInterfaceNumber -cdc_union.bSlaveInterface_list = [cdc_data_interface.bInterfaceNumber] +if include_cdc: + cdc_union.bMasterInterface = cdc_comm_interface.bInterfaceNumber + cdc_union.bSlaveInterface_list = [cdc_data_interface.bInterfaceNumber] + + cdc_call_management.bDataInterface = cdc_data_interface.bInterfaceNumber + +if include_cdc2: + cdc2_union.bMasterInterface = cdc2_comm_interface.bInterfaceNumber + cdc2_union.bSlaveInterface_list = [cdc2_data_interface.bInterfaceNumber] -cdc_call_management.bDataInterface = cdc_data_interface.bInterfaceNumber + cdc2_call_management.bDataInterface = cdc2_data_interface.bInterfaceNumber -cdc_iad = standard.InterfaceAssociationDescriptor( - description="CDC IAD", - bFirstInterface=cdc_comm_interface.bInterfaceNumber, - bInterfaceCount=len(cdc_interfaces), - bFunctionClass=cdc.CDC_CLASS_COMM, # Communications Device Class - bFunctionSubClass=cdc.CDC_SUBCLASS_ACM, # Abstract control model - bFunctionProtocol=cdc.CDC_PROTOCOL_NONE) + +def make_cdc_iad(cdc_comm_interface, name): + return standard.InterfaceAssociationDescriptor( + description="{} IAD".format(name), + bFirstInterface=cdc_comm_interface.bInterfaceNumber, + bInterfaceCount=len(cdc_interfaces), + bFunctionClass=cdc.CDC_CLASS_COMM, # Communications Device Class + bFunctionSubClass=cdc.CDC_SUBCLASS_ACM, # Abstract control model + bFunctionProtocol=cdc.CDC_PROTOCOL_NONE, + ) + + +if include_cdc: + cdc_iad = make_cdc_iad(cdc_comm_interface, "CDC") +if include_cdc2: + cdc2_iad = make_cdc_iad(cdc2_comm_interface, "CDC2") descriptor_list = [] -if 'CDC' in args.devices: +if include_cdc: # Put the CDC IAD just before the CDC interfaces. # There appears to be a bug in the Windows composite USB driver that requests the # HID report descriptor with the wrong interface number if the HID interface is not given @@ -414,68 +589,101 @@ def strings_in_order(cls): descriptor_list.append(cdc_iad) descriptor_list.extend(cdc_interfaces) -if 'MSC' in args.devices: +if include_cdc2: + descriptor_list.append(cdc2_iad) + descriptor_list.extend(cdc2_interfaces) + +if include_msc: descriptor_list.extend(msc_interfaces) -if 'HID' in args.devices: +if include_hid: descriptor_list.extend(hid_interfaces) -if 'AUDIO' in args.devices: +if include_audio: # Only add the control interface because other audio interfaces are managed by it to ensure the # correct ordering. descriptor_list.append(audio_control_interface) +if include_vendor: + descriptor_list.extend(vendor_interfaces) + # Finally, build the composite descriptor. configuration = standard.ConfigurationDescriptor( description="Composite configuration", - wTotalLength=(standard.ConfigurationDescriptor.bLength + - sum([len(bytes(x)) for x in descriptor_list])), - bNumInterfaces=len(interfaces)) + wTotalLength=( + standard.ConfigurationDescriptor.bLength + sum([len(bytes(x)) for x in descriptor_list]) + ), + bNumInterfaces=len(interfaces), + # bus powered (bit 6), remote wakeup (bit 5), + # bit 7 is always 1 and 0-4 are always 0 + # Turn off remote wakeup until we handle it in CircuitPython. + bmAttributes=0x80, + +) descriptor_list.insert(0, configuration) -string_descriptors = [standard.StringDescriptor(string) for string in StringIndex.strings_in_order()] +string_descriptors = [ + standard.StringDescriptor(string) for string in StringIndex.strings_in_order() +] serial_number_descriptor = string_descriptors[SERIAL_NUMBER_INDEX] c_file = args.output_c_file h_file = args.output_h_file -c_file.write("""\ +c_file.write( + """\ #include +#include "tusb.h" #include "py/objtuple.h" #include "shared-bindings/usb_hid/Device.h" #include "{H_FILE_NAME}" -""".format(H_FILE_NAME=h_file.name)) +""".format( + H_FILE_NAME=h_file.name + ) +) -c_file.write("""\ +c_file.write( + """\ // {DESCRIPTION} : {CLASS} -""".format(DESCRIPTION=device.description, - CLASS=device.__class__)) +""".format( + DESCRIPTION=device.description, CLASS=device.__class__ + ) +) -c_file.write("""\ +c_file.write( + """\ const uint8_t usb_desc_dev[] = { -""") +""" +) for b in bytes(device): c_file.write("0x{:02x}, ".format(b)) -c_file.write("""\ +c_file.write( + """\ }; -""") +""" +) -c_file.write("""\ +c_file.write( + """\ const uint8_t usb_desc_cfg[] = { -""") +""" +) # Write out all the regular descriptors as one long array (that's how ASF4 does it). descriptor_length = 0 for descriptor in descriptor_list: - c_file.write("""\ + c_file.write( + """\ // {DESCRIPTION} : {CLASS} -""".format(DESCRIPTION=descriptor.description, - CLASS=descriptor.__class__)) +""".format( + DESCRIPTION=descriptor.description, CLASS=descriptor.__class__ + ) + ) b = bytes(descriptor) notes = descriptor.notes() @@ -493,17 +701,22 @@ def strings_in_order(cls): i += length descriptor_length += len(b) -c_file.write("""\ +c_file.write( + """\ }; -""") +""" +) pointers_to_strings = [] for idx, descriptor in enumerate(string_descriptors): - c_file.write("""\ + c_file.write( + """\ // {DESCRIPTION} : {CLASS} -""".format(DESCRIPTION=descriptor.description, - CLASS=descriptor.__class__)) +""".format( + DESCRIPTION=descriptor.description, CLASS=descriptor.__class__ + ) + ) b = bytes(descriptor) notes = descriptor.notes() @@ -513,45 +726,67 @@ def strings_in_order(cls): variable_name = StringIndex.index_to_variable[idx] if not variable_name: variable_name = "string_descriptor{}".format(idx) + pointers_to_strings.append("{name}".format(name=variable_name)) const = "const " if variable_name == "usb_serial_number": - const = "" - c_file.write("""\ -{const}uint16_t {NAME}[] = {{ -""".format(const=const, NAME=variable_name)) - pointers_to_strings.append("{name}".format(name=variable_name)) - n = 0 - while i < len(b): - length = b[i] - for j in range(length // 2): - c_file.write("0x{:04x}, ".format(b[i + 2*j + 1] << 8 | b[i + 2*j])) - n += 1 - c_file.write("\n") - i += length - c_file.write("""\ -}; -""") - -c_file.write("""\ + length = len(b) + c_file.write( + " uint16_t {NAME}[{length}];\n".format(NAME=variable_name, length=length // 2) + ) + else: + c_file.write( + """\ + const uint16_t {NAME}[] = {{ + """.format( + const=const, NAME=variable_name + ) + ) + n = 0 + while i < len(b): + length = b[i] + for j in range(length // 2): + c_file.write("0x{:04x}, ".format(b[i + 2 * j + 1] << 8 | b[i + 2 * j])) + n += 1 + c_file.write("\n") + i += length + c_file.write( + """\ + }; + """ + ) + +c_file.write( + """\ // array of pointer to string descriptors uint16_t const * const string_desc_arr [] = { -""") -c_file.write(""",\ +""" +) +c_file.write( + """,\ -""".join(pointers_to_strings)) +""".join( + pointers_to_strings + ) +) -c_file.write(""" +c_file.write( + """ }; -""") +""" +) c_file.write("\n") -hid_descriptor_length = len(bytes(combined_hid_report_descriptor)) +if include_hid: + hid_descriptor_length = len(bytes(combined_hid_report_descriptor)) +else: + hid_descriptor_length = 0 -# Now we values we need for the .h file. -h_file.write("""\ +# Now the values we need for the .h file. +h_file.write( + """\ #ifndef MICROPY_INCLUDED_AUTOGEN_USB_DESCRIPTOR_H #define MICROPY_INCLUDED_AUTOGEN_USB_DESCRIPTOR_H @@ -562,61 +797,120 @@ def strings_in_order(cls): extern uint16_t usb_serial_number[{serial_number_length}]; extern uint16_t const * const string_desc_arr [{string_descriptor_length}]; -extern const uint8_t hid_report_descriptor[{hid_report_descriptor_length}]; - #define CFG_TUSB_RHPORT0_MODE ({rhport0_mode}) -#define USB_HID_NUM_DEVICES {hid_num_devices} - // Vendor name included in Inquiry response, max 8 bytes #define CFG_TUD_MSC_VENDOR "{msc_vendor}" // Product name included in Inquiry response, max 16 bytes #define CFG_TUD_MSC_PRODUCT "{msc_product}" -""" -.format(serial_number_length=len(bytes(serial_number_descriptor)) // 2, +""".format( + serial_number_length=len(bytes(serial_number_descriptor)) // 2, device_length=len(bytes(device)), configuration_length=descriptor_length, max_configuration_length=max(hid_descriptor_length, descriptor_length), string_descriptor_length=len(pointers_to_strings), - hid_report_descriptor_length=len(bytes(combined_hid_report_descriptor)), - rhport0_mode='OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED' if args.highspeed else 'OPT_MODE_DEVICE', - hid_num_devices=len(args.hid_devices), + rhport0_mode="OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED" + if args.highspeed + else "OPT_MODE_DEVICE", msc_vendor=args.manufacturer[:8], - msc_product=args.product[:16])) + msc_product=args.product[:16], + ) +) -# Write out the report descriptor and info -c_file.write("""\ +if include_hid: + h_file.write( + """\ +extern const uint8_t hid_report_descriptor[{hid_report_descriptor_length}]; + +#define USB_HID_NUM_DEVICES {hid_num_devices} +""".format( + hid_report_descriptor_length=len(bytes(combined_hid_report_descriptor)), + hid_num_devices=len(args.hid_devices), + ) + ) + +if include_vendor: + h_file.write( + """\ +enum +{ + VENDOR_REQUEST_WEBUSB = 1, + VENDOR_REQUEST_MICROSOFT = 2 +}; + +extern uint8_t const desc_ms_os_20[]; + +// Currently getting compile-time errors in files like tusb_fifo.c +// if we try do define this here (TODO figure this out!) +//extern const tusb_desc_webusb_url_t desc_webusb_url; + +""" + ) + +h_file.write( + """\ +#endif // MICROPY_INCLUDED_AUTOGEN_USB_DESCRIPTOR_H +""" +) + +if include_hid: + # Write out the report descriptor and info + c_file.write( + """\ const uint8_t hid_report_descriptor[{HID_DESCRIPTOR_LENGTH}] = {{ -""".format(HID_DESCRIPTOR_LENGTH=hid_descriptor_length)) +""".format( + HID_DESCRIPTOR_LENGTH=hid_descriptor_length + ) + ) -for b in bytes(combined_hid_report_descriptor): - c_file.write("0x{:02x}, ".format(b)) -c_file.write("""\ + for b in bytes(combined_hid_report_descriptor): + c_file.write("0x{:02x}, ".format(b)) + + c_file.write( + """\ }; -""") +""" + ) -# Write out USB HID report buffer definitions. -for name in args.hid_devices: - c_file.write("""\ + # Write out USB HID report buffer definitions. + for name in args.hid_devices: + c_file.write( + """\ static uint8_t {name}_report_buffer[{report_length}]; -""".format(name=name.lower(), report_length=hid_report_descriptors.HID_DEVICE_DATA[name].report_length)) - - if hid_report_descriptors.HID_DEVICE_DATA[name].out_report_length > 0: - c_file.write("""\ +""".format( + name=name.lower(), + report_length=hid_report_descriptors.HID_DEVICE_DATA[name].report_length, + ) + ) + + if hid_report_descriptors.HID_DEVICE_DATA[name].out_report_length > 0: + c_file.write( + """\ 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)) - -# Write out table of device objects. -c_file.write(""" +""".format( + name=name.lower(), + report_length=hid_report_descriptors.HID_DEVICE_DATA[name].out_report_length, + ) + ) + + # Write out table of device objects. + c_file.write( + """\ usb_hid_device_obj_t usb_hid_devices[] = { -""") -for name in args.hid_devices: - device_data = hid_report_descriptors.HID_DEVICE_DATA[name] - out_report_buffer = '{}_out_report_buffer'.format(name.lower()) if device_data.out_report_length > 0 else 'NULL' - c_file.write("""\ +""" + ) + for name in args.hid_devices: + device_data = hid_report_descriptors.HID_DEVICE_DATA[name] + out_report_buffer = ( + "{}_out_report_buffer".format(name.lower()) + if device_data.out_report_length > 0 + else "NULL" + ) + c_file.write( + """\ {{ .base = {{ .type = &usb_hid_device_type }}, .report_buffer = {name}_report_buffer, @@ -627,34 +921,144 @@ def strings_in_order(cls): .out_report_buffer = {out_report_buffer}, .out_report_length = {out_report_length}, }}, -""".format(name=name.lower(), report_id=report_ids[name], - report_length=device_data.report_length, - usage_page=device_data.usage_page, - usage=device_data.usage, - out_report_buffer=out_report_buffer, - out_report_length=device_data.out_report_length)) -c_file.write("""\ +""".format( + name=name.lower(), + report_id=report_ids[name], + report_length=device_data.report_length, + usage_page=device_data.usage_page, + usage=device_data.usage, + out_report_buffer=out_report_buffer, + out_report_length=device_data.out_report_length, + ) + ) + c_file.write( + """\ }; -""") +""" + ) -# Write out tuple of device objects. -c_file.write(""" + # Write out tuple of device objects. + c_file.write( + """ mp_obj_tuple_t common_hal_usb_hid_devices = {{ .base = {{ .type = &mp_type_tuple, }}, .len = {num_devices}, .items = {{ -""".format(num_devices=len(args.hid_devices))) -for idx in range(len(args.hid_devices)): - c_file.write("""\ +""".format( + num_devices=len(args.hid_devices) + ) + ) + for idx in range(len(args.hid_devices)): + c_file.write( + """\ (mp_obj_t) &usb_hid_devices[{idx}], -""".format(idx=idx)) -c_file.write("""\ +""".format( + idx=idx + ) + ) + c_file.write( + """\ }, }; -""") +""" + ) -h_file.write("""\ -#endif // MICROPY_INCLUDED_AUTOGEN_USB_DESCRIPTOR_H -""") +if include_vendor: + # Mimic what the tinyusb webusb demo does in its main.c file + c_file.write( + """ +#define URL "{webusb_url}" + +const tusb_desc_webusb_url_t desc_webusb_url = +{{ + .bLength = 3 + sizeof(URL) - 1, + .bDescriptorType = 3, // WEBUSB URL type + .bScheme = 1, // 0: http, 1: https, 255: "" + .url = URL +}}; + +// These next two hardcoded descriptors were pulled from the usb_descriptor.c file +// of the tinyusb webusb_serial demo. TODO - this is probably something else to +// integrate into the adafruit_usb_descriptors project... + +//--------------------------------------------------------------------+ +// BOS Descriptor +//--------------------------------------------------------------------+ + +/* Microsoft OS 2.0 registry property descriptor +Per MS requirements https://msdn.microsoft.com/en-us/library/windows/hardware/hh450799(v=vs.85).aspx +device should create DeviceInterfaceGUIDs. It can be done by driver and +in case of real PnP solution device should expose MS "Microsoft OS 2.0 +registry property descriptor". Such descriptor can insert any record +into Windows registry per device/configuration/interface. In our case it +will insert "DeviceInterfaceGUIDs" multistring property. + +GUID is freshly generated and should be OK to use. + +https://developers.google.com/web/fundamentals/native-hardware/build-for-webusb/ +(Section Microsoft OS compatibility descriptors) +*/ + +#define BOS_TOTAL_LEN (TUD_BOS_DESC_LEN + TUD_BOS_WEBUSB_DESC_LEN + TUD_BOS_MICROSOFT_OS_DESC_LEN) + +#define MS_OS_20_DESC_LEN 0xB2 + +// BOS Descriptor is required for webUSB +uint8_t const desc_bos[] = +{{ + // total length, number of device caps + TUD_BOS_DESCRIPTOR(BOS_TOTAL_LEN, 2), + + // Vendor Code, iLandingPage + TUD_BOS_WEBUSB_DESCRIPTOR(VENDOR_REQUEST_WEBUSB, 1), + + // Microsoft OS 2.0 descriptor + TUD_BOS_MS_OS_20_DESCRIPTOR(MS_OS_20_DESC_LEN, VENDOR_REQUEST_MICROSOFT) +}}; + +uint8_t const * tud_descriptor_bos_cb(void) +{{ + return desc_bos; +}} + + +#define ITF_NUM_VENDOR {webusb_interface} // used in this next descriptor + +uint8_t const desc_ms_os_20[] = +{{ + // Set header: length, type, windows version, total length + U16_TO_U8S_LE(0x000A), U16_TO_U8S_LE(MS_OS_20_SET_HEADER_DESCRIPTOR), U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(MS_OS_20_DESC_LEN), + + // Configuration subset header: length, type, configuration index, reserved, configuration total length + U16_TO_U8S_LE(0x0008), U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_CONFIGURATION), 0, 0, U16_TO_U8S_LE(MS_OS_20_DESC_LEN-0x0A), + + // Function Subset header: length, type, first interface, reserved, subset length + U16_TO_U8S_LE(0x0008), U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_FUNCTION), ITF_NUM_VENDOR, 0, U16_TO_U8S_LE(MS_OS_20_DESC_LEN-0x0A-0x08), + + // MS OS 2.0 Compatible ID descriptor: length, type, compatible ID, sub compatible ID + U16_TO_U8S_LE(0x0014), U16_TO_U8S_LE(MS_OS_20_FEATURE_COMPATBLE_ID), 'W', 'I', 'N', 'U', 'S', 'B', 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // sub-compatible + + // MS OS 2.0 Registry property descriptor: length, type + U16_TO_U8S_LE(MS_OS_20_DESC_LEN-0x0A-0x08-0x08-0x14), U16_TO_U8S_LE(MS_OS_20_FEATURE_REG_PROPERTY), + U16_TO_U8S_LE(0x0007), U16_TO_U8S_LE(0x002A), // wPropertyDataType, wPropertyNameLength and PropertyName "DeviceInterfaceGUIDs\0" in UTF-16 + 'D', 0x00, 'e', 0x00, 'v', 0x00, 'i', 0x00, 'c', 0x00, 'e', 0x00, 'I', 0x00, 'n', 0x00, 't', 0x00, 'e', 0x00, + 'r', 0x00, 'f', 0x00, 'a', 0x00, 'c', 0x00, 'e', 0x00, 'G', 0x00, 'U', 0x00, 'I', 0x00, 'D', 0x00, 's', 0x00, 0x00, 0x00, + U16_TO_U8S_LE(0x0050), // wPropertyDataLength + //bPropertyData: “{{975F44D9-0D08-43FD-8B3E-127CA8AFFF9D}}”. + '{{', 0x00, '9', 0x00, '7', 0x00, '5', 0x00, 'F', 0x00, '4', 0x00, '4', 0x00, 'D', 0x00, '9', 0x00, '-', 0x00, + '0', 0x00, 'D', 0x00, '0', 0x00, '8', 0x00, '-', 0x00, '4', 0x00, '3', 0x00, 'F', 0x00, 'D', 0x00, '-', 0x00, + '8', 0x00, 'B', 0x00, '3', 0x00, 'E', 0x00, '-', 0x00, '1', 0x00, '2', 0x00, '7', 0x00, 'C', 0x00, 'A', 0x00, + '8', 0x00, 'A', 0x00, 'F', 0x00, 'F', 0x00, 'F', 0x00, '9', 0x00, 'D', 0x00, '}}', 0x00, 0x00, 0x00, 0x00, 0x00 +}}; + +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 + ) + ) diff --git a/tools/gendoc.py b/tools/gendoc.py index 85411cb4101fe..bf79b3cf5fab6 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 Break(Exception): 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 @@ def next(self): 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 @@ def start(self): 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 @@ def start(self): 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 @@ def para(self, text, indent=''): 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 @@ def add_doc(self, lex): def dump(self, writer): writer.para(self.doc) + class DocConstant(DocItem): def __init__(self, name, descr): super().__init__() @@ -215,6 +222,7 @@ def __init__(self, name, descr): 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 @@ def __init__(self, name, args): 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 @@ def __init__(self, name, args): 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 @@ def __init__(self, name, descr): 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 @@ def new_file(self): 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 @@ def process_method(self, lex, d): 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 @@ def process_constant(self, lex, d): 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 @@ def new_file(self): 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 @@ def validate(self): 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 aaa5b18b1f7b7..827af3a3f0df6 100644 --- a/tools/hid_report_descriptors.py +++ b/tools/hid_report_descriptors.py @@ -18,17 +18,36 @@ # 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 bf74ceeab51b5..f63059ca1b19b 100644 --- a/tools/insert-usb-ids.py +++ b/tools/insert-usb-ids.py @@ -12,15 +12,16 @@ 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 ad23b9d5952e3..f9ffa7642145a 100755 --- a/tools/make-frozen.py +++ b/tools/make-frozen.py @@ -30,6 +30,7 @@ def module_name(f): return f + modules = [] root = sys.argv[1].rstrip("/") @@ -39,7 +40,7 @@ def module_name(f): 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 @@ def module_name(f): # 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 @@ def module_name(f): 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 2f813931e83d4..7c2aede5b9526 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 95090466c477f..9572f8f2aaacd 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 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 @@ class Config: # 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 = 0x1B +MP_BC_LOAD_GLOBAL = 0x1C +MP_BC_LOAD_ATTR = 0x1D MP_BC_STORE_ATTR = 0x26 # load opcode names @@ -71,87 +76,86 @@ class Config: 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 - - 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 - )) + 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 + ) + ) + # this function mirrors that in py/bc.c def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): @@ -159,13 +163,22 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): ip_start = ip f = (opcode_format[opcode >> 2] >> (2 * (opcode & 3))) & 3 if f == MP_OPCODE_QSTR: + if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE: + if ( + opcode == MP_BC_LOAD_NAME + or opcode == MP_BC_LOAD_GLOBAL + or opcode == MP_BC_LOAD_ATTR + or opcode == MP_BC_STORE_ATTR + ): + ip += 1 ip += 3 else: extra_byte = ( 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 +195,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 +264,7 @@ def _unpack_qstr(self, ip): def dump(self): # dump children first for rc in self.raw_codes: - rc.freeze('') + rc.freeze("") # TODO def freeze(self, parent_name): @@ -245,35 +277,44 @@ def freeze(self, parent_name): 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 +324,52 @@ def freeze(self, parent_name): 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)) + extra = "" if sz == 3 else " 0x%02x," % self.bytecode[ip + 3] + print(" {}, {} & 0xff, {} >> 8,{}".format(opcode, qst, qst, extra)) 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 +382,137 @@ def freeze(self, parent_name): 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 +520,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 +535,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 +572,88 @@ 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("const qstr_attr_t mp_qstr_frozen_const_attr[] = {") 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["data"] += len(qstr) - print(' %s,' - % qstrutil.make_bytes(config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr)) - print(' },') - print('};') + qbytes = qstrutil.bytes_cons(qstr, "utf8") + print(" {%d, %d}," % ( + qstrutil.compute_hash(qbytes, config.MICROPY_QSTR_BYTES_IN_HASH), + len(qbytes) + )) + qstr_size["metadata"] += ( + config.MICROPY_QSTR_BYTES_IN_LEN + config.MICROPY_QSTR_BYTES_IN_HASH + ) + qstr_size["data"] += len(qbytes) + print("};") + + # As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len + qstr_pool_alloc = min(len(new), 10) + + 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" % qstr_pool_alloc) + print(" %u, // used entries" % len(new)) + print(" (qstr_attr_t *)mp_qstr_frozen_const_attr,") + print(" {") + for _, _, qstr in new: + print(" \"%s\"," % qstrutil.escape_bytes(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 +661,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 +733,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 5d9f8bc0bacc4..9c217400fb11e 100755 --- a/tools/mpy_cross_all.py +++ b/tools/mpy_cross_all.py @@ -11,14 +11,13 @@ 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 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 b75a2e7238c67..294df317bc882 100755 --- a/tools/preprocess_frozen_modules.py +++ b/tools/preprocess_frozen_modules.py @@ -13,25 +13,35 @@ # 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 9a8b311dc2ade..50535502ea6f3 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 ddf6bb6c40c2b..200f4578a410a 100755 --- a/tools/pyboard.py +++ b/tools/pyboard.py @@ -57,44 +57,49 @@ # 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): + self.tn = 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() def close(self): - try: + if self.tn: self.tn.close() - except: - # the telnet object might not exist yet, so ignore this one - pass def read(self, size=1): while len(self.fifo) < size: @@ -109,7 +114,7 @@ def read(self, size=1): 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 +138,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 +178,7 @@ def write(self, data): 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 +194,16 @@ def __init__(self, cmd): 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 +217,7 @@ def __init__(self, cmd): def close(self): import signal + os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM) def read(self, size=1): @@ -208,36 +231,37 @@ def inWaiting(self): 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 +288,7 @@ def read_until(self, min_num_bytes, ending, timeout=10, data_consumer=None): 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 +296,38 @@ def enter_raw_repl(self): 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 +337,55 @@ def exec_raw_no_follow(self, command): 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 +393,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 +459,11 @@ def execbuffer(buf): # 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 +487,6 @@ def execbuffer(buf): # close the connection to the pyboard pyb.close() + if __name__ == "__main__": main() diff --git a/tools/pydfu.py b/tools/pydfu.py index a6210c603adbc..fd1988a9b36c6 100755 --- a/tools/pydfu.py +++ b/tools/pydfu.py @@ -15,6 +15,7 @@ from __future__ import print_function import argparse +import collections import re import struct import sys @@ -24,61 +25,84 @@ # 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 __dev = None +# Configuration descriptor of the device +__cfg_descr = None + __verbose = None # USB DFU interface __DFU_INTERFACE = 0 import inspect -if 'length' in inspect.getargspec(usb.util.get_string).args: + +if "length" in inspect.getfullargspec(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): return usb.util.get_string(dev, index) +def find_dfu_cfg_descr(descr): + if len(descr) == 9 and descr[0] == 9 and descr[1] == _DFU_DESCRIPTOR_TYPE: + nt = collections.namedtuple( + "CfgDescr", + [ + "bLength", + "bDescriptorType", + "bmAttributes", + "wDetachTimeOut", + "wTransferSize", + "bcdDFUVersion", + ], + ) + return nt(*struct.unpack(" 1: raise ValueError("Multiple DFU devices found") __dev = devices[0] @@ -87,20 +111,41 @@ def init(): # Claim DFU interface usb.util.claim_interface(__dev, __DFU_INTERFACE) - # Clear status - clr_status() + # Find the DFU configuration descriptor, either in the device or interfaces + __cfg_descr = None + for cfg in __dev.configurations(): + __cfg_descr = find_dfu_cfg_descr(cfg.extra_descriptors) + if __cfg_descr: + break + for itf in cfg.interfaces(): + __cfg_descr = find_dfu_cfg_descr(itf.extra_descriptors) + if __cfg_descr: + break + + # Get device into idle state + for attempt in range(4): + status = get_status() + if status == __DFU_STATE_DFU_IDLE: + break + elif status == __DFU_STATE_DFU_DOWNLOAD_IDLE or status == __DFU_STATE_DFU_UPLOAD_IDLE: + abort_request() + else: + clr_status() + + +def abort_request(): + """Sends an abort request.""" + __dev.ctrl_transfer(0x21, __DFU_ABORT, 0, __DFU_INTERFACE, None, __TIMEOUT) 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 +153,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 +210,21 @@ 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(__cfg_descr.wTransferSize, 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 +246,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 +260,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 +270,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 +298,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 +318,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 +331,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 +347,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 +388,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 +414,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 +423,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 +438,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 +472,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 +494,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 +505,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,10 +526,16 @@ 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="") - sys.stdout.flush() + print( + "\r0x{:08x} {:7d} [{}{}] {:3d}% ".format( + addr, size, "=" * done, " " * (width - done), offset * 100 // size + ), + end="", + ) + try: + sys.stdout.flush() + except OSError: + pass # Ignore Windows CLI "WinError 87" on Python 3.6 if offset == size: print("") @@ -488,31 +544,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 +569,7 @@ def main(): init() if args.mass_erase: - print ("Mass erase...") + print("Mass erase...") mass_erase() if args.path: @@ -541,5 +585,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 74b1878f9515c..934412d163165 100755 --- a/tools/tinytest-codegen.py +++ b/tools/tinytest-codegen.py @@ -13,17 +13,19 @@ def escape(s): s = s.decode() lookup = { - '\0': '\\0', - '\t': '\\t', - '\n': '\\n\"\n\"', - '\r': '\\r', - '\\': '\\\\', - '\"': '\\\"', + "\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])) + 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 +34,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 +62,72 @@ def script_to_map(test_file): "}}" ) -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/uncrustify.cfg b/tools/uncrustify.cfg new file mode 100644 index 0000000000000..80542b903e79e --- /dev/null +++ b/tools/uncrustify.cfg @@ -0,0 +1,3093 @@ +# Uncrustify-0.71.0_f + +# +# General options +# + +# The type of line endings. +# +# Default: auto +newlines = auto # lf/crlf/cr/auto + +# The original size of tabs in the input. +# +# Default: 8 +input_tab_size = 8 # unsigned number + +# The size of tabs in the output (only used if align_with_tabs=true). +# +# Default: 8 +output_tab_size = 8 # unsigned number + +# The ASCII value of the string escape char, usually 92 (\) or (Pawn) 94 (^). +# +# Default: 92 +string_escape_char = 92 # unsigned number + +# Alternate string escape char (usually only used for Pawn). +# Only works right before the quote char. +string_escape_char2 = 0 # unsigned number + +# Replace tab characters found in string literals with the escape sequence \t +# instead. +string_replace_tab_chars = false # true/false + +# Allow interpreting '>=' and '>>=' as part of a template in code like +# 'void f(list>=val);'. If true, 'assert(x<0 && y>=3)' will be broken. +# Improvements to template detection may make this option obsolete. +tok_split_gte = false # true/false + +# Disable formatting of NL_CONT ('\\n') ended lines (e.g. multiline macros) +disable_processing_nl_cont = false # true/false + +# Specify the marker used in comments to disable processing of part of the +# file. +# The comment should be used alone in one line. +# +# Default: *INDENT-OFF* +disable_processing_cmt = " *FORMAT-OFF*" # string + +# Specify the marker used in comments to (re)enable processing in a file. +# The comment should be used alone in one line. +# +# Default: *INDENT-ON* +enable_processing_cmt = " *FORMAT-ON*" # string + +# Enable parsing of digraphs. +enable_digraphs = false # true/false + +# Add or remove the UTF-8 BOM (recommend 'remove'). +utf8_bom = ignore # ignore/add/remove/force + +# If the file contains bytes with values between 128 and 255, but is not +# UTF-8, then output as UTF-8. +utf8_byte = false # true/false + +# Force the output encoding to UTF-8. +utf8_force = false # true/false + +# Add or remove space between 'do' and '{'. +sp_do_brace_open = force # ignore/add/remove/force + +# Add or remove space between '}' and 'while'. +sp_brace_close_while = force # ignore/add/remove/force + +# Add or remove space between 'while' and '('. +sp_while_paren_open = force # ignore/add/remove/force + +# +# Spacing options +# + +# Add or remove space around non-assignment symbolic operators ('+', '/', '%', +# '<<', and so forth). +sp_arith = force # ignore/add/remove/force + +# Add or remove space around arithmetic operators '+' and '-'. +# +# Overrides sp_arith. +sp_arith_additive = force # ignore/add/remove/force + +# Add or remove space around assignment operator '=', '+=', etc. +sp_assign = force # ignore/add/remove/force + +# Add or remove space around '=' in C++11 lambda capture specifications. +# +# Overrides sp_assign. +sp_cpp_lambda_assign = ignore # ignore/add/remove/force + +# Add or remove space after the capture specification of a C++11 lambda when +# an argument list is present, as in '[] (int x){ ... }'. +sp_cpp_lambda_square_paren = ignore # ignore/add/remove/force + +# Add or remove space after the capture specification of a C++11 lambda with +# no argument list is present, as in '[] { ... }'. +sp_cpp_lambda_square_brace = ignore # ignore/add/remove/force + +# Add or remove space after the argument list of a C++11 lambda, as in +# '[](int x) { ... }'. +sp_cpp_lambda_paren_brace = ignore # ignore/add/remove/force + +# Add or remove space between a lambda body and its call operator of an +# immediately invoked lambda, as in '[]( ... ){ ... } ( ... )'. +sp_cpp_lambda_fparen = ignore # ignore/add/remove/force + +# Add or remove space around assignment operator '=' in a prototype. +# +# If set to ignore, use sp_assign. +sp_assign_default = ignore # ignore/add/remove/force + +# Add or remove space before assignment operator '=', '+=', etc. +# +# Overrides sp_assign. +sp_before_assign = ignore # ignore/add/remove/force + +# Add or remove space after assignment operator '=', '+=', etc. +# +# Overrides sp_assign. +sp_after_assign = ignore # ignore/add/remove/force + +# Add or remove space in 'NS_ENUM ('. +sp_enum_paren = ignore # ignore/add/remove/force + +# Add or remove space around assignment '=' in enum. +sp_enum_assign = ignore # ignore/add/remove/force + +# Add or remove space before assignment '=' in enum. +# +# Overrides sp_enum_assign. +sp_enum_before_assign = ignore # ignore/add/remove/force + +# Add or remove space after assignment '=' in enum. +# +# Overrides sp_enum_assign. +sp_enum_after_assign = ignore # ignore/add/remove/force + +# Add or remove space around assignment ':' in enum. +sp_enum_colon = ignore # ignore/add/remove/force + +# Add or remove space around preprocessor '##' concatenation operator. +# +# Default: add +sp_pp_concat = remove # ignore/add/remove/force + +# Add or remove space after preprocessor '#' stringify operator. +# Also affects the '#@' charizing operator. +sp_pp_stringify = ignore # ignore/add/remove/force + +# Add or remove space before preprocessor '#' stringify operator +# as in '#define x(y) L#y'. +sp_before_pp_stringify = ignore # ignore/add/remove/force + +# Add or remove space around boolean operators '&&' and '||'. +sp_bool = force # ignore/add/remove/force + +# Add or remove space around compare operator '<', '>', '==', etc. +sp_compare = force # ignore/add/remove/force + +# Add or remove space inside '(' and ')'. +sp_inside_paren = remove # ignore/add/remove/force + +# Add or remove space between nested parentheses, i.e. '((' vs. ') )'. +sp_paren_paren = remove # ignore/add/remove/force + +# Add or remove space between back-to-back parentheses, i.e. ')(' vs. ') ('. +sp_cparen_oparen = ignore # ignore/add/remove/force + +# Whether to balance spaces inside nested parentheses. +sp_balance_nested_parens = false # true/false + +# Add or remove space between ')' and '{'. +sp_paren_brace = force # ignore/add/remove/force + +# Add or remove space between nested braces, i.e. '{{' vs '{ {'. +sp_brace_brace = force # ignore/add/remove/force + +# Add or remove space before pointer star '*'. +sp_before_ptr_star = force # ignore/add/remove/force + +# Add or remove space before pointer star '*' that isn't followed by a +# variable name. If set to ignore, sp_before_ptr_star is used instead. +sp_before_unnamed_ptr_star = force # ignore/add/remove/force + +# Add or remove space between pointer stars '*'. +sp_between_ptr_star = remove # ignore/add/remove/force + +# Add or remove space after pointer star '*', if followed by a word. +# +# Overrides sp_type_func. +sp_after_ptr_star = remove # ignore/add/remove/force + +# Add or remove space after pointer caret '^', if followed by a word. +sp_after_ptr_block_caret = ignore # ignore/add/remove/force + +# Add or remove space after pointer star '*', if followed by a qualifier. +sp_after_ptr_star_qualifier = remove # ignore/add/remove/force + +# Add or remove space after a pointer star '*', if followed by a function +# prototype or function definition. +# +# Overrides sp_after_ptr_star and sp_type_func. +sp_after_ptr_star_func = ignore # ignore/add/remove/force + +# Add or remove space after a pointer star '*', if followed by an open +# parenthesis, as in 'void* (*)(). +sp_ptr_star_paren = ignore # ignore/add/remove/force + +# Add or remove space before a pointer star '*', if followed by a function +# prototype or function definition. +sp_before_ptr_star_func = force # ignore/add/remove/force + +# Add or remove space before a reference sign '&'. +sp_before_byref = ignore # ignore/add/remove/force + +# Add or remove space before a reference sign '&' that isn't followed by a +# variable name. If set to ignore, sp_before_byref is used instead. +sp_before_unnamed_byref = ignore # ignore/add/remove/force + +# Add or remove space after reference sign '&', if followed by a word. +# +# Overrides sp_type_func. +sp_after_byref = ignore # ignore/add/remove/force + +# Add or remove space after a reference sign '&', if followed by a function +# prototype or function definition. +# +# Overrides sp_after_byref and sp_type_func. +sp_after_byref_func = ignore # ignore/add/remove/force + +# Add or remove space before a reference sign '&', if followed by a function +# prototype or function definition. +sp_before_byref_func = ignore # ignore/add/remove/force + +# Add or remove space between type and word. +# +# Default: force +sp_after_type = force # ignore/add/remove/force + +# Add or remove space between 'decltype(...)' and word. +sp_after_decltype = ignore # ignore/add/remove/force + +# (D) Add or remove space before the parenthesis in the D constructs +# 'template Foo(' and 'class Foo('. +sp_before_template_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'template' and '<'. +# If set to ignore, sp_before_angle is used. +sp_template_angle = ignore # ignore/add/remove/force + +# Add or remove space before '<'. +sp_before_angle = ignore # ignore/add/remove/force + +# Add or remove space inside '<' and '>'. +sp_inside_angle = ignore # ignore/add/remove/force + +# Add or remove space inside '<>'. +sp_inside_angle_empty = ignore # ignore/add/remove/force + +# Add or remove space between '>' and ':'. +sp_angle_colon = ignore # ignore/add/remove/force + +# Add or remove space after '>'. +sp_after_angle = ignore # ignore/add/remove/force + +# Add or remove space between '>' and '(' as found in 'new List(foo);'. +sp_angle_paren = ignore # ignore/add/remove/force + +# Add or remove space between '>' and '()' as found in 'new List();'. +sp_angle_paren_empty = ignore # ignore/add/remove/force + +# Add or remove space between '>' and a word as in 'List m;' or +# 'template static ...'. +sp_angle_word = ignore # ignore/add/remove/force + +# Add or remove space between '>' and '>' in '>>' (template stuff). +# +# Default: add +sp_angle_shift = add # ignore/add/remove/force + +# (C++11) Permit removal of the space between '>>' in 'foo >'. Note +# that sp_angle_shift cannot remove the space without this option. +sp_permit_cpp11_shift = false # true/false + +# Add or remove space before '(' of control statements ('if', 'for', 'switch', +# 'while', etc.). +sp_before_sparen = force # ignore/add/remove/force + +# Add or remove space inside '(' and ')' of control statements. +sp_inside_sparen = remove # ignore/add/remove/force + +# Add or remove space after '(' of control statements. +# +# Overrides sp_inside_sparen. +sp_inside_sparen_open = ignore # ignore/add/remove/force + +# Add or remove space before ')' of control statements. +# +# Overrides sp_inside_sparen. +sp_inside_sparen_close = ignore # ignore/add/remove/force + +# Add or remove space after ')' of control statements. +sp_after_sparen = ignore # ignore/add/remove/force + +# Add or remove space between ')' and '{' of of control statements. +sp_sparen_brace = force # ignore/add/remove/force + +# (D) Add or remove space between 'invariant' and '('. +sp_invariant_paren = ignore # ignore/add/remove/force + +# (D) Add or remove space after the ')' in 'invariant (C) c'. +sp_after_invariant_paren = ignore # ignore/add/remove/force + +# Add or remove space before empty statement ';' on 'if', 'for' and 'while'. +sp_special_semi = ignore # ignore/add/remove/force + +# Add or remove space before ';'. +# +# Default: remove +sp_before_semi = remove # ignore/add/remove/force + +# Add or remove space before ';' in non-empty 'for' statements. +sp_before_semi_for = ignore # ignore/add/remove/force + +# Add or remove space before a semicolon of an empty part of a for statement. +sp_before_semi_for_empty = ignore # ignore/add/remove/force + +# Add or remove space after ';', except when followed by a comment. +# +# Default: add +sp_after_semi = add # ignore/add/remove/force + +# Add or remove space after ';' in non-empty 'for' statements. +# +# Default: force +sp_after_semi_for = force # ignore/add/remove/force + +# Add or remove space after the final semicolon of an empty part of a for +# statement, as in 'for ( ; ; )'. +sp_after_semi_for_empty = ignore # ignore/add/remove/force + +# Add or remove space before '[' (except '[]'). +sp_before_square = ignore # ignore/add/remove/force + +# Add or remove space before '[' for a variable definition. +# +# Default: remove +sp_before_vardef_square = remove # ignore/add/remove/force + +# Add or remove space before '[' for asm block. +sp_before_square_asm_block = ignore # ignore/add/remove/force + +# Add or remove space before '[]'. +sp_before_squares = ignore # ignore/add/remove/force + +# Add or remove space before C++17 structured bindings. +sp_cpp_before_struct_binding = ignore # ignore/add/remove/force + +# Add or remove space inside a non-empty '[' and ']'. +sp_inside_square = ignore # ignore/add/remove/force + +# (OC) Add or remove space inside a non-empty Objective-C boxed array '@[' and +# ']'. If set to ignore, sp_inside_square is used. +sp_inside_square_oc_array = ignore # ignore/add/remove/force + +# Add or remove space after ',', i.e. 'a,b' vs. 'a, b'. +sp_after_comma = ignore # ignore/add/remove/force + +# Add or remove space before ','. +# +# Default: remove +sp_before_comma = remove # ignore/add/remove/force + +# (C#) Add or remove space between ',' and ']' in multidimensional array type +# like 'int[,,]'. +sp_after_mdatype_commas = ignore # ignore/add/remove/force + +# (C#) Add or remove space between '[' and ',' in multidimensional array type +# like 'int[,,]'. +sp_before_mdatype_commas = ignore # ignore/add/remove/force + +# (C#) Add or remove space between ',' in multidimensional array type +# like 'int[,,]'. +sp_between_mdatype_commas = ignore # ignore/add/remove/force + +# Add or remove space between an open parenthesis and comma, +# i.e. '(,' vs. '( ,'. +# +# Default: force +sp_paren_comma = force # ignore/add/remove/force + +# Add or remove space before the variadic '...' when preceded by a +# non-punctuator. +sp_before_ellipsis = ignore # ignore/add/remove/force + +# Add or remove space between a type and '...'. +sp_type_ellipsis = ignore # ignore/add/remove/force + +# (D) Add or remove space between a type and '?'. +sp_type_question = ignore # ignore/add/remove/force + +# Add or remove space between ')' and '...'. +sp_paren_ellipsis = ignore # ignore/add/remove/force + +# Add or remove space between ')' and a qualifier such as 'const'. +sp_paren_qualifier = ignore # ignore/add/remove/force + +# Add or remove space between ')' and 'noexcept'. +sp_paren_noexcept = ignore # ignore/add/remove/force + +# Add or remove space after class ':'. +sp_after_class_colon = ignore # ignore/add/remove/force + +# Add or remove space before class ':'. +sp_before_class_colon = ignore # ignore/add/remove/force + +# Add or remove space after class constructor ':'. +sp_after_constr_colon = ignore # ignore/add/remove/force + +# Add or remove space before class constructor ':'. +sp_before_constr_colon = ignore # ignore/add/remove/force + +# Add or remove space before case ':'. +# +# Default: remove +sp_before_case_colon = remove # ignore/add/remove/force + +# Add or remove space between 'operator' and operator sign. +sp_after_operator = ignore # ignore/add/remove/force + +# Add or remove space between the operator symbol and the open parenthesis, as +# in 'operator ++('. +sp_after_operator_sym = ignore # ignore/add/remove/force + +# Overrides sp_after_operator_sym when the operator has no arguments, as in +# 'operator *()'. +sp_after_operator_sym_empty = ignore # ignore/add/remove/force + +# Add or remove space after C/D cast, i.e. 'cast(int)a' vs. 'cast(int) a' or +# '(int)a' vs. '(int) a'. +sp_after_cast = remove # ignore/add/remove/force + +# Add or remove spaces inside cast parentheses. +sp_inside_paren_cast = remove # ignore/add/remove/force + +# Add or remove space between the type and open parenthesis in a C++ cast, +# i.e. 'int(exp)' vs. 'int (exp)'. +sp_cpp_cast_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'sizeof' and '('. +sp_sizeof_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'sizeof' and '...'. +sp_sizeof_ellipsis = ignore # ignore/add/remove/force + +# Add or remove space between 'sizeof...' and '('. +sp_sizeof_ellipsis_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'decltype' and '('. +sp_decltype_paren = ignore # ignore/add/remove/force + +# (Pawn) Add or remove space after the tag keyword. +sp_after_tag = ignore # ignore/add/remove/force + +# Add or remove space inside enum '{' and '}'. +sp_inside_braces_enum = ignore # ignore/add/remove/force + +# Add or remove space inside struct/union '{' and '}'. +sp_inside_braces_struct = ignore # ignore/add/remove/force + +# (OC) Add or remove space inside Objective-C boxed dictionary '{' and '}' +sp_inside_braces_oc_dict = ignore # ignore/add/remove/force + +# Add or remove space after open brace in an unnamed temporary +# direct-list-initialization. +sp_after_type_brace_init_lst_open = ignore # ignore/add/remove/force + +# Add or remove space before close brace in an unnamed temporary +# direct-list-initialization. +sp_before_type_brace_init_lst_close = ignore # ignore/add/remove/force + +# Add or remove space inside an unnamed temporary direct-list-initialization. +sp_inside_type_brace_init_lst = ignore # ignore/add/remove/force + +# Add or remove space inside '{' and '}'. +sp_inside_braces = ignore # ignore/add/remove/force + +# Add or remove space inside '{}'. +sp_inside_braces_empty = ignore # ignore/add/remove/force + +# Add or remove space around trailing return operator '->'. +sp_trailing_return = ignore # ignore/add/remove/force + +# Add or remove space between return type and function name. A minimum of 1 +# is forced except for pointer return types. +sp_type_func = ignore # ignore/add/remove/force + +# Add or remove space between type and open brace of an unnamed temporary +# direct-list-initialization. +sp_type_brace_init_lst = ignore # ignore/add/remove/force + +# Add or remove space between function name and '(' on function declaration. +sp_func_proto_paren = remove # ignore/add/remove/force + +# Add or remove space between function name and '()' on function declaration +# without parameters. +sp_func_proto_paren_empty = remove # ignore/add/remove/force + +# Add or remove space between function name and '(' with a typedef specifier. +sp_func_type_paren = remove # ignore/add/remove/force + +# Add or remove space between alias name and '(' of a non-pointer function type typedef. +sp_func_def_paren = remove # ignore/add/remove/force + +# Add or remove space between function name and '()' on function definition +# without parameters. +sp_func_def_paren_empty = remove # ignore/add/remove/force + +# Add or remove space inside empty function '()'. +# Overrides sp_after_angle unless use_sp_after_angle_always is set to true. +sp_inside_fparens = remove # ignore/add/remove/force + +# Add or remove space inside function '(' and ')'. +sp_inside_fparen = remove # ignore/add/remove/force + +# Add or remove space inside the first parentheses in a function type, as in +# 'void (*x)(...)'. +sp_inside_tparen = remove # ignore/add/remove/force + +# Add or remove space between the ')' and '(' in a function type, as in +# 'void (*x)(...)'. +sp_after_tparen_close = remove # ignore/add/remove/force + +# Add or remove space between ']' and '(' when part of a function call. +sp_square_fparen = remove # ignore/add/remove/force + +# Add or remove space between ')' and '{' of function. +sp_fparen_brace = force # ignore/add/remove/force + +# Add or remove space between ')' and '{' of s function call in object +# initialization. +# +# Overrides sp_fparen_brace. +sp_fparen_brace_initializer = ignore # ignore/add/remove/force + +# (Java) Add or remove space between ')' and '{{' of double brace initializer. +sp_fparen_dbrace = ignore # ignore/add/remove/force + +# Add or remove space between function name and '(' on function calls. +sp_func_call_paren = remove # ignore/add/remove/force + +# Add or remove space between function name and '()' on function calls without +# parameters. If set to ignore (the default), sp_func_call_paren is used. +sp_func_call_paren_empty = remove # ignore/add/remove/force + +# Add or remove space between the user function name and '(' on function +# calls. You need to set a keyword to be a user function in the config file, +# like: +# set func_call_user tr _ i18n +sp_func_call_user_paren = ignore # ignore/add/remove/force + +# Add or remove space inside user function '(' and ')'. +sp_func_call_user_inside_fparen = ignore # ignore/add/remove/force + +# Add or remove space between nested parentheses with user functions, +# i.e. '((' vs. '( ('. +sp_func_call_user_paren_paren = ignore # ignore/add/remove/force + +# Add or remove space between a constructor/destructor and the open +# parenthesis. +sp_func_class_paren = ignore # ignore/add/remove/force + +# Add or remove space between a constructor without parameters or destructor +# and '()'. +sp_func_class_paren_empty = ignore # ignore/add/remove/force + +# Add or remove space between 'return' and '('. +sp_return_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'return' and '{'. +sp_return_brace = ignore # ignore/add/remove/force + +# Add or remove space between '__attribute__' and '('. +sp_attribute_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'defined' and '(' in '#if defined (FOO)'. +sp_defined_paren = remove # ignore/add/remove/force + +# Add or remove space between 'throw' and '(' in 'throw (something)'. +sp_throw_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'throw' and anything other than '(' as in +# '@throw [...];'. +sp_after_throw = ignore # ignore/add/remove/force + +# Add or remove space between 'catch' and '(' in 'catch (something) { }'. +# If set to ignore, sp_before_sparen is used. +sp_catch_paren = ignore # ignore/add/remove/force + +# (OC) Add or remove space between '@catch' and '(' +# in '@catch (something) { }'. If set to ignore, sp_catch_paren is used. +sp_oc_catch_paren = ignore # ignore/add/remove/force + +# (OC) Add or remove space before Objective-C protocol list +# as in '@protocol Protocol' or '@interface MyClass : NSObject'. +sp_before_oc_proto_list = ignore # ignore/add/remove/force + +# (OC) Add or remove space between class name and '(' +# in '@interface className(categoryName):BaseClass' +sp_oc_classname_paren = ignore # ignore/add/remove/force + +# (D) Add or remove space between 'version' and '(' +# in 'version (something) { }'. If set to ignore, sp_before_sparen is used. +sp_version_paren = ignore # ignore/add/remove/force + +# (D) Add or remove space between 'scope' and '(' +# in 'scope (something) { }'. If set to ignore, sp_before_sparen is used. +sp_scope_paren = ignore # ignore/add/remove/force + +# Add or remove space between 'super' and '(' in 'super (something)'. +# +# Default: remove +sp_super_paren = remove # ignore/add/remove/force + +# Add or remove space between 'this' and '(' in 'this (something)'. +# +# Default: remove +sp_this_paren = remove # ignore/add/remove/force + +# Add or remove space between a macro name and its definition. +sp_macro = ignore # ignore/add/remove/force + +# Add or remove space between a macro function ')' and its definition. +sp_macro_func = ignore # ignore/add/remove/force + +# Add or remove space between 'else' and '{' if on the same line. +sp_else_brace = force # ignore/add/remove/force + +# Add or remove space between '}' and 'else' if on the same line. +sp_brace_else = force # ignore/add/remove/force + +# Add or remove space between '}' and the name of a typedef on the same line. +sp_brace_typedef = ignore # ignore/add/remove/force + +# Add or remove space before the '{' of a 'catch' statement, if the '{' and +# 'catch' are on the same line, as in 'catch (decl) {'. +sp_catch_brace = ignore # ignore/add/remove/force + +# (OC) Add or remove space before the '{' of a '@catch' statement, if the '{' +# and '@catch' are on the same line, as in '@catch (decl) {'. +# If set to ignore, sp_catch_brace is used. +sp_oc_catch_brace = ignore # ignore/add/remove/force + +# Add or remove space between '}' and 'catch' if on the same line. +sp_brace_catch = ignore # ignore/add/remove/force + +# (OC) Add or remove space between '}' and '@catch' if on the same line. +# If set to ignore, sp_brace_catch is used. +sp_oc_brace_catch = ignore # ignore/add/remove/force + +# Add or remove space between 'finally' and '{' if on the same line. +sp_finally_brace = ignore # ignore/add/remove/force + +# Add or remove space between '}' and 'finally' if on the same line. +sp_brace_finally = ignore # ignore/add/remove/force + +# Add or remove space between 'try' and '{' if on the same line. +sp_try_brace = ignore # ignore/add/remove/force + +# Add or remove space between get/set and '{' if on the same line. +sp_getset_brace = ignore # ignore/add/remove/force + +# Add or remove space between a variable and '{' for C++ uniform +# initialization. +sp_word_brace_init_lst = ignore # ignore/add/remove/force + +# Add or remove space between a variable and '{' for a namespace. +# +# Default: add +sp_word_brace_ns = add # ignore/add/remove/force + +# Add or remove space before the '::' operator. +sp_before_dc = ignore # ignore/add/remove/force + +# Add or remove space after the '::' operator. +sp_after_dc = ignore # ignore/add/remove/force + +# (D) Add or remove around the D named array initializer ':' operator. +sp_d_array_colon = ignore # ignore/add/remove/force + +# Add or remove space after the '!' (not) unary operator. +# +# Default: remove +sp_not = remove # ignore/add/remove/force + +# Add or remove space after the '~' (invert) unary operator. +# +# Default: remove +sp_inv = remove # ignore/add/remove/force + +# Add or remove space after the '&' (address-of) unary operator. This does not +# affect the spacing after a '&' that is part of a type. +# +# Default: remove +sp_addr = remove # ignore/add/remove/force + +# Add or remove space around the '.' or '->' operators. +# +# Default: remove +sp_member = remove # ignore/add/remove/force + +# Add or remove space after the '*' (dereference) unary operator. This does +# not affect the spacing after a '*' that is part of a type. +# +# Default: remove +sp_deref = remove # ignore/add/remove/force + +# Add or remove space after '+' or '-', as in 'x = -5' or 'y = +7'. +# +# Default: remove +sp_sign = remove # ignore/add/remove/force + +# Add or remove space between '++' and '--' the word to which it is being +# applied, as in '(--x)' or 'y++;'. +# +# Default: remove +sp_incdec = remove # ignore/add/remove/force + +# Add or remove space before a backslash-newline at the end of a line. +# +# Default: add +sp_before_nl_cont = add # ignore/add/remove/force + +# (OC) Add or remove space after the scope '+' or '-', as in '-(void) foo;' +# or '+(int) bar;'. +sp_after_oc_scope = ignore # ignore/add/remove/force + +# (OC) Add or remove space after the colon in message specs, +# i.e. '-(int) f:(int) x;' vs. '-(int) f: (int) x;'. +sp_after_oc_colon = ignore # ignore/add/remove/force + +# (OC) Add or remove space before the colon in message specs, +# i.e. '-(int) f: (int) x;' vs. '-(int) f : (int) x;'. +sp_before_oc_colon = ignore # ignore/add/remove/force + +# (OC) Add or remove space after the colon in immutable dictionary expression +# 'NSDictionary *test = @{@"foo" :@"bar"};'. +sp_after_oc_dict_colon = ignore # ignore/add/remove/force + +# (OC) Add or remove space before the colon in immutable dictionary expression +# 'NSDictionary *test = @{@"foo" :@"bar"};'. +sp_before_oc_dict_colon = ignore # ignore/add/remove/force + +# (OC) Add or remove space after the colon in message specs, +# i.e. '[object setValue:1];' vs. '[object setValue: 1];'. +sp_after_send_oc_colon = ignore # ignore/add/remove/force + +# (OC) Add or remove space before the colon in message specs, +# i.e. '[object setValue:1];' vs. '[object setValue :1];'. +sp_before_send_oc_colon = ignore # ignore/add/remove/force + +# (OC) Add or remove space after the (type) in message specs, +# i.e. '-(int)f: (int) x;' vs. '-(int)f: (int)x;'. +sp_after_oc_type = ignore # ignore/add/remove/force + +# (OC) Add or remove space after the first (type) in message specs, +# i.e. '-(int) f:(int)x;' vs. '-(int)f:(int)x;'. +sp_after_oc_return_type = ignore # ignore/add/remove/force + +# (OC) Add or remove space between '@selector' and '(', +# i.e. '@selector(msgName)' vs. '@selector (msgName)'. +# Also applies to '@protocol()' constructs. +sp_after_oc_at_sel = ignore # ignore/add/remove/force + +# (OC) Add or remove space between '@selector(x)' and the following word, +# i.e. '@selector(foo) a:' vs. '@selector(foo)a:'. +sp_after_oc_at_sel_parens = ignore # ignore/add/remove/force + +# (OC) Add or remove space inside '@selector' parentheses, +# i.e. '@selector(foo)' vs. '@selector( foo )'. +# Also applies to '@protocol()' constructs. +sp_inside_oc_at_sel_parens = ignore # ignore/add/remove/force + +# (OC) Add or remove space before a block pointer caret, +# i.e. '^int (int arg){...}' vs. ' ^int (int arg){...}'. +sp_before_oc_block_caret = ignore # ignore/add/remove/force + +# (OC) Add or remove space after a block pointer caret, +# i.e. '^int (int arg){...}' vs. '^ int (int arg){...}'. +sp_after_oc_block_caret = ignore # ignore/add/remove/force + +# (OC) Add or remove space between the receiver and selector in a message, +# as in '[receiver selector ...]'. +sp_after_oc_msg_receiver = ignore # ignore/add/remove/force + +# (OC) Add or remove space after '@property'. +sp_after_oc_property = ignore # ignore/add/remove/force + +# (OC) Add or remove space between '@synchronized' and the open parenthesis, +# i.e. '@synchronized(foo)' vs. '@synchronized (foo)'. +sp_after_oc_synchronized = ignore # ignore/add/remove/force + +# Add or remove space around the ':' in 'b ? t : f'. +sp_cond_colon = ignore # ignore/add/remove/force + +# Add or remove space before the ':' in 'b ? t : f'. +# +# Overrides sp_cond_colon. +sp_cond_colon_before = ignore # ignore/add/remove/force + +# Add or remove space after the ':' in 'b ? t : f'. +# +# Overrides sp_cond_colon. +sp_cond_colon_after = ignore # ignore/add/remove/force + +# Add or remove space around the '?' in 'b ? t : f'. +sp_cond_question = ignore # ignore/add/remove/force + +# Add or remove space before the '?' in 'b ? t : f'. +# +# Overrides sp_cond_question. +sp_cond_question_before = ignore # ignore/add/remove/force + +# Add or remove space after the '?' in 'b ? t : f'. +# +# Overrides sp_cond_question. +sp_cond_question_after = ignore # ignore/add/remove/force + +# In the abbreviated ternary form '(a ?: b)', add or remove space between '?' +# and ':'. +# +# Overrides all other sp_cond_* options. +sp_cond_ternary_short = ignore # ignore/add/remove/force + +# Fix the spacing between 'case' and the label. Only 'ignore' and 'force' make +# sense here. +sp_case_label = ignore # ignore/add/remove/force + +# (D) Add or remove space around the D '..' operator. +sp_range = ignore # ignore/add/remove/force + +# Add or remove space after ':' in a Java/C++11 range-based 'for', +# as in 'for (Type var : expr)'. +sp_after_for_colon = ignore # ignore/add/remove/force + +# Add or remove space before ':' in a Java/C++11 range-based 'for', +# as in 'for (Type var : expr)'. +sp_before_for_colon = ignore # ignore/add/remove/force + +# (D) Add or remove space between 'extern' and '(' as in 'extern (C)'. +sp_extern_paren = ignore # ignore/add/remove/force + +# Add or remove space after the opening of a C++ comment, +# i.e. '// A' vs. '//A'. +sp_cmt_cpp_start = add # ignore/add/remove/force + +# If true, space is added with sp_cmt_cpp_start will be added after doxygen +# sequences like '///', '///<', '//!' and '//!<'. +sp_cmt_cpp_doxygen = false # true/false + +# If true, space is added with sp_cmt_cpp_start will be added after Qt +# translator or meta-data comments like '//:', '//=', and '//~'. +sp_cmt_cpp_qttr = false # true/false + +# Add or remove space between #else or #endif and a trailing comment. +sp_endif_cmt = ignore # ignore/add/remove/force + +# Add or remove space after 'new', 'delete' and 'delete[]'. +sp_after_new = ignore # ignore/add/remove/force + +# Add or remove space between 'new' and '(' in 'new()'. +sp_between_new_paren = ignore # ignore/add/remove/force + +# Add or remove space between ')' and type in 'new(foo) BAR'. +sp_after_newop_paren = ignore # ignore/add/remove/force + +# Add or remove space inside parenthesis of the new operator +# as in 'new(foo) BAR'. +sp_inside_newop_paren = ignore # ignore/add/remove/force + +# Add or remove space after the open parenthesis of the new operator, +# as in 'new(foo) BAR'. +# +# Overrides sp_inside_newop_paren. +sp_inside_newop_paren_open = ignore # ignore/add/remove/force + +# Add or remove space before the close parenthesis of the new operator, +# as in 'new(foo) BAR'. +# +# Overrides sp_inside_newop_paren. +sp_inside_newop_paren_close = ignore # ignore/add/remove/force + +# Add or remove space before a trailing or embedded comment. +sp_before_tr_emb_cmt = ignore # ignore/add/remove/force + +# Number of spaces before a trailing or embedded comment. +sp_num_before_tr_emb_cmt = 0 # unsigned number + +# (Java) Add or remove space between an annotation and the open parenthesis. +sp_annotation_paren = ignore # ignore/add/remove/force + +# If true, vbrace tokens are dropped to the previous token and skipped. +sp_skip_vbrace_tokens = false # true/false + +# Add or remove space after 'noexcept'. +sp_after_noexcept = ignore # ignore/add/remove/force + +# Add or remove space after '_'. +sp_vala_after_translation = ignore # ignore/add/remove/force + +# If true, a is inserted after #define. +force_tab_after_define = false # true/false + +# +# Indenting options +# + +# The number of columns to indent per level. Usually 2, 3, 4, or 8. +# +# Default: 8 +indent_columns = 4 # unsigned number + +# The continuation indent. If non-zero, this overrides the indent of '(', '[' +# and '=' continuation indents. Negative values are OK; negative value is +# absolute and not increased for each '(' or '[' level. +# +# For FreeBSD, this is set to 4. +indent_continue = 0 # number + +# The continuation indent, only for class header line(s). If non-zero, this +# overrides the indent of 'class' continuation indents. +indent_continue_class_head = 0 # unsigned number + +# Whether to indent empty lines (i.e. lines which contain only spaces before +# the newline character). +indent_single_newlines = false # true/false + +# The continuation indent for func_*_param if they are true. If non-zero, this +# overrides the indent. +indent_param = 0 # unsigned number + +# How to use tabs when indenting code. +# +# 0: Spaces only +# 1: Indent with tabs to brace level, align with spaces (default) +# 2: Indent and align with tabs, using spaces when not on a tabstop +# +# Default: 1 +indent_with_tabs = 0 # unsigned number + +# Whether to indent comments that are not at a brace level with tabs on a +# tabstop. Requires indent_with_tabs=2. If false, will use spaces. +indent_cmt_with_tabs = false # true/false + +# Whether to indent strings broken by '\' so that they line up. +indent_align_string = false # true/false + +# The number of spaces to indent multi-line XML strings. +# Requires indent_align_string=true. +indent_xml_string = 0 # unsigned number + +# Spaces to indent '{' from level. +indent_brace = 0 # unsigned number + +# Whether braces are indented to the body level. +indent_braces = false # true/false + +# Whether to disable indenting function braces if indent_braces=true. +indent_braces_no_func = false # true/false + +# Whether to disable indenting class braces if indent_braces=true. +indent_braces_no_class = false # true/false + +# Whether to disable indenting struct braces if indent_braces=true. +indent_braces_no_struct = false # true/false + +# Whether to indent based on the size of the brace parent, +# i.e. 'if' => 3 spaces, 'for' => 4 spaces, etc. +indent_brace_parent = false # true/false + +# Whether to indent based on the open parenthesis instead of the open brace +# in '({\n'. +indent_paren_open_brace = false # true/false + +# (C#) Whether to indent the brace of a C# delegate by another level. +indent_cs_delegate_brace = false # true/false + +# (C#) Whether to indent a C# delegate (to handle delegates with no brace) by +# another level. +indent_cs_delegate_body = false # true/false + +# Whether to indent the body of a 'namespace'. +indent_namespace = false # true/false + +# Whether to indent only the first namespace, and not any nested namespaces. +# Requires indent_namespace=true. +indent_namespace_single_indent = false # true/false + +# The number of spaces to indent a namespace block. +# If set to zero, use the value indent_columns +indent_namespace_level = 0 # unsigned number + +# If the body of the namespace is longer than this number, it won't be +# indented. Requires indent_namespace=true. 0 means no limit. +indent_namespace_limit = 0 # unsigned number + +# Whether the 'extern "C"' body is indented. +indent_extern = false # true/false + +# Whether the 'class' body is indented. +indent_class = false # true/false + +# Whether to indent the stuff after a leading base class colon. +indent_class_colon = false # true/false + +# Whether to indent based on a class colon instead of the stuff after the +# colon. Requires indent_class_colon=true. +indent_class_on_colon = false # true/false + +# Whether to indent the stuff after a leading class initializer colon. +indent_constr_colon = false # true/false + +# Virtual indent from the ':' for member initializers. +# +# Default: 2 +indent_ctor_init_leading = 2 # unsigned number + +# Additional indent for constructor initializer list. +# Negative values decrease indent down to the first column. +indent_ctor_init = 0 # number + +# Whether to indent 'if' following 'else' as a new block under the 'else'. +# If false, 'else\nif' is treated as 'else if' for indenting purposes. +indent_else_if = false # true/false + +# Amount to indent variable declarations after a open brace. +# +# <0: Relative +# >=0: Absolute +indent_var_def_blk = 0 # number + +# Whether to indent continued variable declarations instead of aligning. +indent_var_def_cont = false # true/false + +# Whether to indent continued shift expressions ('<<' and '>>') instead of +# aligning. Set align_left_shift=false when enabling this. +indent_shift = false # true/false + +# Whether to force indentation of function definitions to start in column 1. +indent_func_def_force_col1 = false # true/false + +# Whether to indent continued function call parameters one indent level, +# rather than aligning parameters under the open parenthesis. +indent_func_call_param = true # true/false + +# Whether to indent continued function definition parameters one indent level, +# rather than aligning parameters under the open parenthesis. +indent_func_def_param = true # true/false + +# for function definitions, only if indent_func_def_param is false +# Allows to align params when appropriate and indent them when not +# behave as if it was true if paren position is more than this value +# if paren position is more than the option value +indent_func_def_param_paren_pos_threshold = 0 # unsigned number + +# Whether to indent continued function call prototype one indent level, +# rather than aligning parameters under the open parenthesis. +indent_func_proto_param = true # true/false + +# Whether to indent continued function call declaration one indent level, +# rather than aligning parameters under the open parenthesis. +indent_func_class_param = true # true/false + +# Whether to indent continued class variable constructors one indent level, +# rather than aligning parameters under the open parenthesis. +indent_func_ctor_var_param = true # true/false + +# Whether to indent continued template parameter list one indent level, +# rather than aligning parameters under the open parenthesis. +indent_template_param = true # true/false + +# Double the indent for indent_func_xxx_param options. +# Use both values of the options indent_columns and indent_param. +indent_func_param_double = false # true/false + +# Indentation column for standalone 'const' qualifier on a function +# prototype. +indent_func_const = 0 # unsigned number + +# Indentation column for standalone 'throw' qualifier on a function +# prototype. +indent_func_throw = 0 # unsigned number + +# How to indent within a macro followed by a brace on the same line +# This allows reducing the indent in macros that have (for example) +# `do { ... } while (0)` blocks bracketing them. +# +# true: add an indent for the brace on the same line as the macro +# false: do not add an indent for the brace on the same line as the macro +# +# Default: true +indent_macro_brace = true # true/false + +# The number of spaces to indent a continued '->' or '.'. +# Usually set to 0, 1, or indent_columns. +indent_member = 0 # unsigned number + +# Whether lines broken at '.' or '->' should be indented by a single indent. +# The indent_member option will not be effective if this is set to true. +indent_member_single = false # true/false + +# Spaces to indent single line ('//') comments on lines before code. +indent_sing_line_comments = 0 # unsigned number + +# When opening a paren for a control statement (if, for, while, etc), increase +# the indent level by this value. Negative values decrease the indent level. +indent_sparen_extra = 0 # number + +# Whether to indent trailing single line ('//') comments relative to the code +# instead of trying to keep the same absolute column. +indent_relative_single_line_comments = false # true/false + +# Spaces to indent 'case' from 'switch'. Usually 0 or indent_columns. +indent_switch_case = indent_columns # unsigned number + +# indent 'break' with 'case' from 'switch'. +indent_switch_break_with_case = false # true/false + +# Whether to indent preprocessor statements inside of switch statements. +# +# Default: true +indent_switch_pp = true # true/false + +# Spaces to shift the 'case' line, without affecting any other lines. +# Usually 0. +indent_case_shift = 0 # unsigned number + +# Spaces to indent '{' from 'case'. By default, the brace will appear under +# the 'c' in case. Usually set to 0 or indent_columns. Negative values are OK. +indent_case_brace = 0 # number + +# Whether to indent comments found in first column. +indent_col1_comment = false # true/false + +# Whether to indent multi string literal in first column. +indent_col1_multi_string_literal = false # true/false + +# How to indent goto labels. +# +# >0: Absolute column where 1 is the leftmost column +# <=0: Subtract from brace indent +# +# Default: 1 +indent_label = -indent_columns # number + +# How to indent access specifiers that are followed by a +# colon. +# +# >0: Absolute column where 1 is the leftmost column +# <=0: Subtract from brace indent +# +# Default: 1 +indent_access_spec = 1 # number + +# Whether to indent the code after an access specifier by one level. +# If true, this option forces 'indent_access_spec=0'. +indent_access_spec_body = false # true/false + +# If an open parenthesis is followed by a newline, whether to indent the next +# line so that it lines up after the open parenthesis (not recommended). +indent_paren_nl = false # true/false + +# How to indent a close parenthesis after a newline. +# +# 0: Indent to body level (default) +# 1: Align under the open parenthesis +# 2: Indent to the brace level +indent_paren_close = 0 # unsigned number + +# Whether to indent the open parenthesis of a function definition, +# if the parenthesis is on its own line. +indent_paren_after_func_def = false # true/false + +# Whether to indent the open parenthesis of a function declaration, +# if the parenthesis is on its own line. +indent_paren_after_func_decl = false # true/false + +# Whether to indent the open parenthesis of a function call, +# if the parenthesis is on its own line. +indent_paren_after_func_call = false # true/false + +# Whether to indent a comma when inside a parenthesis. +# If true, aligns under the open parenthesis. +indent_comma_paren = false # true/false + +# Whether to indent a Boolean operator when inside a parenthesis. +# If true, aligns under the open parenthesis. +indent_bool_paren = false # true/false + +# Whether to indent a semicolon when inside a for parenthesis. +# If true, aligns under the open for parenthesis. +indent_semicolon_for_paren = false # true/false + +# Whether to align the first expression to following ones +# if indent_bool_paren=true. +indent_first_bool_expr = false # true/false + +# Whether to align the first expression to following ones +# if indent_semicolon_for_paren=true. +indent_first_for_expr = false # true/false + +# If an open square is followed by a newline, whether to indent the next line +# so that it lines up after the open square (not recommended). +indent_square_nl = false # true/false + +# (ESQL/C) Whether to preserve the relative indent of 'EXEC SQL' bodies. +indent_preserve_sql = false # true/false + +# Whether to align continued statements at the '='. If false or if the '=' is +# followed by a newline, the next line is indent one tab. +# +# Default: true +indent_align_assign = false # true/false + +# If true, the indentation of the chunks after a '=' sequence will be set at +# LHS token indentation column before '='. +indent_off_after_assign = false # true/false + +# Whether to align continued statements at the '('. If false or the '(' is +# followed by a newline, the next line indent is one tab. +# +# Default: true +indent_align_paren = false # true/false + +# (OC) Whether to indent Objective-C code inside message selectors. +indent_oc_inside_msg_sel = false # true/false + +# (OC) Whether to indent Objective-C blocks at brace level instead of usual +# rules. +indent_oc_block = false # true/false + +# (OC) Indent for Objective-C blocks in a message relative to the parameter +# name. +# +# =0: Use indent_oc_block rules +# >0: Use specified number of spaces to indent +indent_oc_block_msg = 0 # unsigned number + +# (OC) Minimum indent for subsequent parameters +indent_oc_msg_colon = 0 # unsigned number + +# (OC) Whether to prioritize aligning with initial colon (and stripping spaces +# from lines, if necessary). +# +# Default: true +indent_oc_msg_prioritize_first_colon = true # true/false + +# (OC) Whether to indent blocks the way that Xcode does by default +# (from the keyword if the parameter is on its own line; otherwise, from the +# previous indentation level). Requires indent_oc_block_msg=true. +indent_oc_block_msg_xcode_style = false # true/false + +# (OC) Whether to indent blocks from where the brace is, relative to a +# message keyword. Requires indent_oc_block_msg=true. +indent_oc_block_msg_from_keyword = false # true/false + +# (OC) Whether to indent blocks from where the brace is, relative to a message +# colon. Requires indent_oc_block_msg=true. +indent_oc_block_msg_from_colon = false # true/false + +# (OC) Whether to indent blocks from where the block caret is. +# Requires indent_oc_block_msg=true. +indent_oc_block_msg_from_caret = false # true/false + +# (OC) Whether to indent blocks from where the brace caret is. +# Requires indent_oc_block_msg=true. +indent_oc_block_msg_from_brace = false # true/false + +# When indenting after virtual brace open and newline add further spaces to +# reach this minimum indent. +indent_min_vbrace_open = 0 # unsigned number + +# Whether to add further spaces after regular indent to reach next tabstop +# when identing after virtual brace open and newline. +indent_vbrace_open_on_tabstop = false # true/false + +# How to indent after a brace followed by another token (not a newline). +# true: indent all contained lines to match the token +# false: indent all contained lines to match the brace +# +# Default: true +indent_token_after_brace = true # true/false + +# Whether to indent the body of a C++11 lambda. +indent_cpp_lambda_body = false # true/false + +# How to indent compound literals that are being returned. +# true: add both the indent from return & the compound literal open brace (ie: +# 2 indent levels) +# false: only indent 1 level, don't add the indent for the open brace, only add +# the indent for the return. +# +# Default: true +indent_compound_literal_return = true # true/false + +# (C#) Whether to indent a 'using' block if no braces are used. +# +# Default: true +indent_using_block = true # true/false + +# How to indent the continuation of ternary operator. +# +# 0: Off (default) +# 1: When the `if_false` is a continuation, indent it under `if_false` +# 2: When the `:` is a continuation, indent it under `?` +indent_ternary_operator = 0 # unsigned number + +# Whether to indent the statments inside ternary operator. +indent_inside_ternary_operator = false # true/false + +# If true, the indentation of the chunks after a `return` sequence will be set at return indentation column. +indent_off_after_return = false # true/false + +# If true, the indentation of the chunks after a `return new` sequence will be set at return indentation column. +indent_off_after_return_new = false # true/false + +# If true, the tokens after return are indented with regular single indentation. By default (false) the indentation is after the return token. +indent_single_after_return = false # true/false + +# Whether to ignore indent and alignment for 'asm' blocks (i.e. assume they +# have their own indentation). +indent_ignore_asm_block = false # true/false + +# +# Newline adding and removing options +# + +# Whether to collapse empty blocks between '{' and '}'. +nl_collapse_empty_body = false # true/false + +# Don't split one-line braced assignments, as in 'foo_t f = { 1, 2 };'. +nl_assign_leave_one_liners = false # true/false + +# Don't split one-line braced statements inside a 'class xx { }' body. +nl_class_leave_one_liners = false # true/false + +# Don't split one-line enums, as in 'enum foo { BAR = 15 };' +nl_enum_leave_one_liners = false # true/false + +# Don't split one-line get or set functions. +nl_getset_leave_one_liners = false # true/false + +# (C#) Don't split one-line property get or set functions. +nl_cs_property_leave_one_liners = false # true/false + +# Don't split one-line function definitions, as in 'int foo() { return 0; }'. +# might modify nl_func_type_name +nl_func_leave_one_liners = false # true/false + +# Don't split one-line C++11 lambdas, as in '[]() { return 0; }'. +nl_cpp_lambda_leave_one_liners = false # true/false + +# Don't split one-line if/else statements, as in 'if(...) b++;'. +nl_if_leave_one_liners = false # true/false + +# Don't split one-line while statements, as in 'while(...) b++;'. +nl_while_leave_one_liners = false # true/false + +# Don't split one-line for statements, as in 'for(...) b++;'. +nl_for_leave_one_liners = false # true/false + +# (OC) Don't split one-line Objective-C messages. +nl_oc_msg_leave_one_liner = false # true/false + +# (OC) Add or remove newline between method declaration and '{'. +nl_oc_mdef_brace = ignore # ignore/add/remove/force + +# (OC) Add or remove newline between Objective-C block signature and '{'. +nl_oc_block_brace = ignore # ignore/add/remove/force + +# (OC) Add or remove blank line before '@interface' statement. +nl_oc_before_interface = ignore # ignore/add/remove/force + +# (OC) Add or remove blank line before '@implementation' statement. +nl_oc_before_implementation = ignore # ignore/add/remove/force + +# (OC) Add or remove blank line before '@end' statement. +nl_oc_before_end = ignore # ignore/add/remove/force + +# (OC) Add or remove newline between '@interface' and '{'. +nl_oc_interface_brace = ignore # ignore/add/remove/force + +# (OC) Add or remove newline between '@implementation' and '{'. +nl_oc_implementation_brace = ignore # ignore/add/remove/force + +# Add or remove newlines at the start of the file. +nl_start_of_file = ignore # ignore/add/remove/force + +# The minimum number of newlines at the start of the file (only used if +# nl_start_of_file is 'add' or 'force'). +nl_start_of_file_min = 0 # unsigned number + +# Add or remove newline at the end of the file. +nl_end_of_file = ignore # ignore/add/remove/force + +# The minimum number of newlines at the end of the file (only used if +# nl_end_of_file is 'add' or 'force'). +nl_end_of_file_min = 0 # unsigned number + +# Add or remove newline between '=' and '{'. +nl_assign_brace = ignore # ignore/add/remove/force + +# (D) Add or remove newline between '=' and '['. +nl_assign_square = ignore # ignore/add/remove/force + +# Add or remove newline between '[]' and '{'. +nl_tsquare_brace = ignore # ignore/add/remove/force + +# (D) Add or remove newline after '= ['. Will also affect the newline before +# the ']'. +nl_after_square_assign = ignore # ignore/add/remove/force + +# Add or remove newline between a function call's ')' and '{', as in +# 'list_for_each(item, &list) { }'. +nl_fcall_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'enum' and '{'. +nl_enum_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'enum' and 'class'. +nl_enum_class = ignore # ignore/add/remove/force + +# Add or remove newline between 'enum class' and the identifier. +nl_enum_class_identifier = ignore # ignore/add/remove/force + +# Add or remove newline between 'enum class' type and ':'. +nl_enum_identifier_colon = ignore # ignore/add/remove/force + +# Add or remove newline between 'enum class identifier :' and type. +nl_enum_colon_type = ignore # ignore/add/remove/force + +# Add or remove newline between 'struct and '{'. +nl_struct_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'union' and '{'. +nl_union_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'if' and '{'. +nl_if_brace = remove # ignore/add/remove/force + +# Add or remove newline between '}' and 'else'. +nl_brace_else = remove # ignore/add/remove/force + +# Add or remove newline between 'else if' and '{'. If set to ignore, +# nl_if_brace is used instead. +nl_elseif_brace = remove # ignore/add/remove/force + +# Add or remove newline between 'else' and '{'. +nl_else_brace = remove # ignore/add/remove/force + +# Add or remove newline between 'else' and 'if'. +nl_else_if = ignore # ignore/add/remove/force + +# Add or remove newline before '{' opening brace +nl_before_opening_brace_func_class_def = ignore # ignore/add/remove/force + +# Add or remove newline before 'if'/'else if' closing parenthesis. +nl_before_if_closing_paren = ignore # ignore/add/remove/force + +# Add or remove newline between '}' and 'finally'. +nl_brace_finally = ignore # ignore/add/remove/force + +# Add or remove newline between 'finally' and '{'. +nl_finally_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'try' and '{'. +nl_try_brace = ignore # ignore/add/remove/force + +# Add or remove newline between get/set and '{'. +nl_getset_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'for' and '{'. +nl_for_brace = ignore # ignore/add/remove/force + +# Add or remove newline before the '{' of a 'catch' statement, as in +# 'catch (decl) {'. +nl_catch_brace = ignore # ignore/add/remove/force + +# (OC) Add or remove newline before the '{' of a '@catch' statement, as in +# '@catch (decl) {'. If set to ignore, nl_catch_brace is used. +nl_oc_catch_brace = ignore # ignore/add/remove/force + +# Add or remove newline between '}' and 'catch'. +nl_brace_catch = ignore # ignore/add/remove/force + +# (OC) Add or remove newline between '}' and '@catch'. If set to ignore, +# nl_brace_catch is used. +nl_oc_brace_catch = ignore # ignore/add/remove/force + +# Add or remove newline between '}' and ']'. +nl_brace_square = ignore # ignore/add/remove/force + +# Add or remove newline between '}' and ')' in a function invocation. +nl_brace_fparen = ignore # ignore/add/remove/force + +# Add or remove newline between 'while' and '{'. +nl_while_brace = remove # ignore/add/remove/force + +# (D) Add or remove newline between 'scope (x)' and '{'. +nl_scope_brace = ignore # ignore/add/remove/force + +# (D) Add or remove newline between 'unittest' and '{'. +nl_unittest_brace = ignore # ignore/add/remove/force + +# (D) Add or remove newline between 'version (x)' and '{'. +nl_version_brace = ignore # ignore/add/remove/force + +# (C#) Add or remove newline between 'using' and '{'. +nl_using_brace = ignore # ignore/add/remove/force + +# Add or remove newline between two open or close braces. Due to general +# newline/brace handling, REMOVE may not work. +nl_brace_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'do' and '{'. +nl_do_brace = ignore # ignore/add/remove/force + +# Add or remove newline between '}' and 'while' of 'do' statement. +nl_brace_while = ignore # ignore/add/remove/force + +# Add or remove newline between 'switch' and '{'. +nl_switch_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'synchronized' and '{'. +nl_synchronized_brace = ignore # ignore/add/remove/force + +# Add a newline between ')' and '{' if the ')' is on a different line than the +# if/for/etc. +# +# Overrides nl_for_brace, nl_if_brace, nl_switch_brace, nl_while_switch and +# nl_catch_brace. +nl_multi_line_cond = false # true/false + +# Add a newline after '(' if an if/for/while/switch condition spans multiple +# lines +nl_multi_line_sparen_open = ignore # ignore/add/remove/force + +# Add a newline before ')' if an if/for/while/switch condition spans multiple +# lines. Overrides nl_before_if_closing_paren if both are specified. +nl_multi_line_sparen_close = ignore # ignore/add/remove/force + +# Force a newline in a define after the macro name for multi-line defines. +nl_multi_line_define = false # true/false + +# Whether to add a newline before 'case', and a blank line before a 'case' +# statement that follows a ';' or '}'. +nl_before_case = false # true/false + +# Whether to add a newline after a 'case' statement. +nl_after_case = true # true/false + +# Add or remove newline between a case ':' and '{'. +# +# Overrides nl_after_case. +nl_case_colon_brace = remove # ignore/add/remove/force + +# Add or remove newline between ')' and 'throw'. +nl_before_throw = ignore # ignore/add/remove/force + +# Add or remove newline between 'namespace' and '{'. +nl_namespace_brace = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<...>' of a template class. +nl_template_class = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<...>' of a template class declaration. +# +# Overrides nl_template_class. +nl_template_class_decl = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<>' of a specialized class declaration. +# +# Overrides nl_template_class_decl. +nl_template_class_decl_special = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<...>' of a template class definition. +# +# Overrides nl_template_class. +nl_template_class_def = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<>' of a specialized class definition. +# +# Overrides nl_template_class_def. +nl_template_class_def_special = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<...>' of a template function. +nl_template_func = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<...>' of a template function +# declaration. +# +# Overrides nl_template_func. +nl_template_func_decl = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<>' of a specialized function +# declaration. +# +# Overrides nl_template_func_decl. +nl_template_func_decl_special = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<...>' of a template function +# definition. +# +# Overrides nl_template_func. +nl_template_func_def = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<>' of a specialized function +# definition. +# +# Overrides nl_template_func_def. +nl_template_func_def_special = ignore # ignore/add/remove/force + +# Add or remove newline after 'template<...>' of a template variable. +nl_template_var = ignore # ignore/add/remove/force + +# Add or remove newline between 'template<...>' and 'using' of a templated +# type alias. +nl_template_using = ignore # ignore/add/remove/force + +# Add or remove newline between 'class' and '{'. +nl_class_brace = ignore # ignore/add/remove/force + +# Add or remove newline before or after (depending on pos_class_comma, +# may not be IGNORE) each',' in the base class list. +nl_class_init_args = ignore # ignore/add/remove/force + +# Add or remove newline after each ',' in the constructor member +# initialization. Related to nl_constr_colon, pos_constr_colon and +# pos_constr_comma. +nl_constr_init_args = ignore # ignore/add/remove/force + +# Add or remove newline before first element, after comma, and after last +# element, in 'enum'. +nl_enum_own_lines = ignore # ignore/add/remove/force + +# Add or remove newline between return type and function name in a function +# definition. +# might be modified by nl_func_leave_one_liners +nl_func_type_name = ignore # ignore/add/remove/force + +# Add or remove newline between return type and function name inside a class +# definition. If set to ignore, nl_func_type_name or nl_func_proto_type_name +# is used instead. +nl_func_type_name_class = ignore # ignore/add/remove/force + +# Add or remove newline between class specification and '::' +# in 'void A::f() { }'. Only appears in separate member implementation (does +# not appear with in-line implementation). +nl_func_class_scope = ignore # ignore/add/remove/force + +# Add or remove newline between function scope and name, as in +# 'void A :: f() { }'. +nl_func_scope_name = ignore # ignore/add/remove/force + +# Add or remove newline between return type and function name in a prototype. +nl_func_proto_type_name = ignore # ignore/add/remove/force + +# Add or remove newline between a function name and the opening '(' in the +# declaration. +nl_func_paren = ignore # ignore/add/remove/force + +# Overrides nl_func_paren for functions with no parameters. +nl_func_paren_empty = ignore # ignore/add/remove/force + +# Add or remove newline between a function name and the opening '(' in the +# definition. +nl_func_def_paren = ignore # ignore/add/remove/force + +# Overrides nl_func_def_paren for functions with no parameters. +nl_func_def_paren_empty = ignore # ignore/add/remove/force + +# Add or remove newline between a function name and the opening '(' in the +# call. +nl_func_call_paren = ignore # ignore/add/remove/force + +# Overrides nl_func_call_paren for functions with no parameters. +nl_func_call_paren_empty = ignore # ignore/add/remove/force + +# Add or remove newline after '(' in a function declaration. +nl_func_decl_start = ignore # ignore/add/remove/force + +# Add or remove newline after '(' in a function definition. +nl_func_def_start = ignore # ignore/add/remove/force + +# Overrides nl_func_decl_start when there is only one parameter. +nl_func_decl_start_single = ignore # ignore/add/remove/force + +# Overrides nl_func_def_start when there is only one parameter. +nl_func_def_start_single = ignore # ignore/add/remove/force + +# Whether to add a newline after '(' in a function declaration if '(' and ')' +# are in different lines. If false, nl_func_decl_start is used instead. +nl_func_decl_start_multi_line = false # true/false + +# Whether to add a newline after '(' in a function definition if '(' and ')' +# are in different lines. If false, nl_func_def_start is used instead. +nl_func_def_start_multi_line = false # true/false + +# Add or remove newline after each ',' in a function declaration. +nl_func_decl_args = ignore # ignore/add/remove/force + +# Add or remove newline after each ',' in a function definition. +nl_func_def_args = ignore # ignore/add/remove/force + +# Add or remove newline after each ',' in a function call. +nl_func_call_args = ignore # ignore/add/remove/force + +# Whether to add a newline after each ',' in a function declaration if '(' +# and ')' are in different lines. If false, nl_func_decl_args is used instead. +nl_func_decl_args_multi_line = false # true/false + +# Whether to add a newline after each ',' in a function definition if '(' +# and ')' are in different lines. If false, nl_func_def_args is used instead. +nl_func_def_args_multi_line = false # true/false + +# Add or remove newline before the ')' in a function declaration. +nl_func_decl_end = ignore # ignore/add/remove/force + +# Add or remove newline before the ')' in a function definition. +nl_func_def_end = ignore # ignore/add/remove/force + +# Overrides nl_func_decl_end when there is only one parameter. +nl_func_decl_end_single = ignore # ignore/add/remove/force + +# Overrides nl_func_def_end when there is only one parameter. +nl_func_def_end_single = ignore # ignore/add/remove/force + +# Whether to add a newline before ')' in a function declaration if '(' and ')' +# are in different lines. If false, nl_func_decl_end is used instead. +nl_func_decl_end_multi_line = false # true/false + +# Whether to add a newline before ')' in a function definition if '(' and ')' +# are in different lines. If false, nl_func_def_end is used instead. +nl_func_def_end_multi_line = false # true/false + +# Add or remove newline between '()' in a function declaration. +nl_func_decl_empty = ignore # ignore/add/remove/force + +# Add or remove newline between '()' in a function definition. +nl_func_def_empty = ignore # ignore/add/remove/force + +# Add or remove newline between '()' in a function call. +nl_func_call_empty = ignore # ignore/add/remove/force + +# Whether to add a newline after '(' in a function call, +# has preference over nl_func_call_start_multi_line. +nl_func_call_start = ignore # ignore/add/remove/force + +# Whether to add a newline before ')' in a function call. +nl_func_call_end = ignore # ignore/add/remove/force + +# Whether to add a newline after '(' in a function call if '(' and ')' are in +# different lines. +nl_func_call_start_multi_line = false # true/false + +# Whether to add a newline after each ',' in a function call if '(' and ')' +# are in different lines. +nl_func_call_args_multi_line = false # true/false + +# Whether to add a newline before ')' in a function call if '(' and ')' are in +# different lines. +nl_func_call_end_multi_line = false # true/false + +# Whether to respect nl_func_call_XXX option incase of closure args. +nl_func_call_args_multi_line_ignore_closures = false # true/false + +# Whether to add a newline after '<' of a template parameter list. +nl_template_start = false # true/false + +# Whether to add a newline after each ',' in a template parameter list. +nl_template_args = false # true/false + +# Whether to add a newline before '>' of a template parameter list. +nl_template_end = false # true/false + +# (OC) Whether to put each Objective-C message parameter on a separate line. +# See nl_oc_msg_leave_one_liner. +nl_oc_msg_args = false # true/false + +# Add or remove newline between function signature and '{'. +nl_fdef_brace = remove # ignore/add/remove/force + +# Add or remove newline between function signature and '{', +# if signature ends with ')'. Overrides nl_fdef_brace. +nl_fdef_brace_cond = ignore # ignore/add/remove/force + +# Add or remove newline between C++11 lambda signature and '{'. +nl_cpp_ldef_brace = ignore # ignore/add/remove/force + +# Add or remove newline between 'return' and the return expression. +nl_return_expr = ignore # ignore/add/remove/force + +# Whether to add a newline after semicolons, except in 'for' statements. +nl_after_semicolon = true # true/false + +# (Java) Add or remove newline between the ')' and '{{' of the double brace +# initializer. +nl_paren_dbrace_open = ignore # ignore/add/remove/force + +# Whether to add a newline after the type in an unnamed temporary +# direct-list-initialization. +nl_type_brace_init_lst = ignore # ignore/add/remove/force + +# Whether to add a newline after the open brace in an unnamed temporary +# direct-list-initialization. +nl_type_brace_init_lst_open = ignore # ignore/add/remove/force + +# Whether to add a newline before the close brace in an unnamed temporary +# direct-list-initialization. +nl_type_brace_init_lst_close = ignore # ignore/add/remove/force + +# Whether to add a newline after '{'. This also adds a newline before the +# matching '}'. +nl_after_brace_open = false # true/false + +# Whether to add a newline between the open brace and a trailing single-line +# comment. Requires nl_after_brace_open=true. +nl_after_brace_open_cmt = false # true/false + +# Whether to add a newline after a virtual brace open with a non-empty body. +# These occur in un-braced if/while/do/for statement bodies. +nl_after_vbrace_open = false # true/false + +# Whether to add a newline after a virtual brace open with an empty body. +# These occur in un-braced if/while/do/for statement bodies. +nl_after_vbrace_open_empty = false # true/false + +# Whether to add a newline after '}'. Does not apply if followed by a +# necessary ';'. +nl_after_brace_close = false # true/false + +# Whether to add a newline after a virtual brace close, +# as in 'if (foo) a++; return;'. +nl_after_vbrace_close = false # true/false + +# Add or remove newline between the close brace and identifier, +# as in 'struct { int a; } b;'. Affects enumerations, unions and +# structures. If set to ignore, uses nl_after_brace_close. +nl_brace_struct_var = ignore # ignore/add/remove/force + +# Whether to alter newlines in '#define' macros. +nl_define_macro = false # true/false + +# Whether to alter newlines between consecutive parenthesis closes. The number +# of closing parentheses in a line will depend on respective open parenthesis +# lines. +nl_squeeze_paren_close = false # true/false + +# Whether to remove blanks after '#ifxx' and '#elxx', or before '#elxx' and +# '#endif'. Does not affect top-level #ifdefs. +nl_squeeze_ifdef = false # true/false + +# Makes the nl_squeeze_ifdef option affect the top-level #ifdefs as well. +nl_squeeze_ifdef_top_level = false # true/false + +# Add or remove blank line before 'if'. +nl_before_if = ignore # ignore/add/remove/force + +# Add or remove blank line after 'if' statement. Add/Force work only if the +# next token is not a closing brace. +nl_after_if = ignore # ignore/add/remove/force + +# Add or remove blank line before 'for'. +nl_before_for = ignore # ignore/add/remove/force + +# Add or remove blank line after 'for' statement. +nl_after_for = ignore # ignore/add/remove/force + +# Add or remove blank line before 'while'. +nl_before_while = ignore # ignore/add/remove/force + +# Add or remove blank line after 'while' statement. +nl_after_while = ignore # ignore/add/remove/force + +# Add or remove blank line before 'switch'. +nl_before_switch = ignore # ignore/add/remove/force + +# Add or remove blank line after 'switch' statement. +nl_after_switch = ignore # ignore/add/remove/force + +# Add or remove blank line before 'synchronized'. +nl_before_synchronized = ignore # ignore/add/remove/force + +# Add or remove blank line after 'synchronized' statement. +nl_after_synchronized = ignore # ignore/add/remove/force + +# Add or remove blank line before 'do'. +nl_before_do = ignore # ignore/add/remove/force + +# Add or remove blank line after 'do/while' statement. +nl_after_do = ignore # ignore/add/remove/force + +# Whether to put a blank line before 'return' statements, unless after an open +# brace. +nl_before_return = false # true/false + +# Whether to put a blank line after 'return' statements, unless followed by a +# close brace. +nl_after_return = false # true/false + +# Whether to put a blank line before a member '.' or '->' operators. +nl_before_member = ignore # ignore/add/remove/force + +# (Java) Whether to put a blank line after a member '.' or '->' operators. +nl_after_member = ignore # ignore/add/remove/force + +# Whether to double-space commented-entries in 'struct'/'union'/'enum'. +nl_ds_struct_enum_cmt = false # true/false + +# Whether to force a newline before '}' of a 'struct'/'union'/'enum'. +# (Lower priority than eat_blanks_before_close_brace.) +nl_ds_struct_enum_close_brace = false # true/false + +# Add or remove newline before or after (depending on pos_class_colon) a class +# colon, as in 'class Foo : public Bar'. +nl_class_colon = ignore # ignore/add/remove/force + +# Add or remove newline around a class constructor colon. The exact position +# depends on nl_constr_init_args, pos_constr_colon and pos_constr_comma. +nl_constr_colon = ignore # ignore/add/remove/force + +# Whether to collapse a two-line namespace, like 'namespace foo\n{ decl; }' +# into a single line. If true, prevents other brace newline rules from turning +# such code into four lines. +nl_namespace_two_to_one_liner = false # true/false + +# Whether to remove a newline in simple unbraced if statements, turning them +# into one-liners, as in 'if(b)\n i++;' => 'if(b) i++;'. +nl_create_if_one_liner = false # true/false + +# Whether to remove a newline in simple unbraced for statements, turning them +# into one-liners, as in 'for (...)\n stmt;' => 'for (...) stmt;'. +nl_create_for_one_liner = false # true/false + +# Whether to remove a newline in simple unbraced while statements, turning +# them into one-liners, as in 'while (expr)\n stmt;' => 'while (expr) stmt;'. +nl_create_while_one_liner = false # true/false + +# Whether to collapse a function definition whose body (not counting braces) +# is only one line so that the entire definition (prototype, braces, body) is +# a single line. +nl_create_func_def_one_liner = false # true/false + +# Whether to collapse a function definition whose body (not counting braces) +# is only one line so that the entire definition (prototype, braces, body) is +# a single line. +nl_create_list_one_liner = false # true/false + +# Whether to split one-line simple unbraced if statements into two lines by +# adding a newline, as in 'if(b) i++;'. +nl_split_if_one_liner = true # true/false + +# Whether to split one-line simple unbraced for statements into two lines by +# adding a newline, as in 'for (...) stmt;'. +nl_split_for_one_liner = true # true/false + +# Whether to split one-line simple unbraced while statements into two lines by +# adding a newline, as in 'while (expr) stmt;'. +nl_split_while_one_liner = true # true/false + +# +# Blank line options +# + +# The maximum number of consecutive newlines (3 = 2 blank lines). +nl_max = 0 # unsigned number + +# The maximum number of consecutive newlines in a function. +nl_max_blank_in_func = 0 # unsigned number + +# The number of newlines before a function prototype. +nl_before_func_body_proto = 0 # unsigned number + +# The number of newlines before a multi-line function definition. +nl_before_func_body_def = 0 # unsigned number + +# The number of newlines before a class constructor/destructor prototype. +nl_before_func_class_proto = 0 # unsigned number + +# The number of newlines before a class constructor/destructor definition. +nl_before_func_class_def = 0 # unsigned number + +# The number of newlines after a function prototype. +nl_after_func_proto = 0 # unsigned number + +# The number of newlines after a function prototype, if not followed by +# another function prototype. +nl_after_func_proto_group = 0 # unsigned number + +# The number of newlines after a class constructor/destructor prototype. +nl_after_func_class_proto = 0 # unsigned number + +# The number of newlines after a class constructor/destructor prototype, +# if not followed by another constructor/destructor prototype. +nl_after_func_class_proto_group = 0 # unsigned number + +# Whether one-line method definitions inside a class body should be treated +# as if they were prototypes for the purposes of adding newlines. +# +# Requires nl_class_leave_one_liners=true. Overrides nl_before_func_body_def +# and nl_before_func_class_def for one-liners. +nl_class_leave_one_liner_groups = false # true/false + +# The number of newlines after '}' of a multi-line function body. +nl_after_func_body = 0 # unsigned number + +# The number of newlines after '}' of a multi-line function body in a class +# declaration. Also affects class constructors/destructors. +# +# Overrides nl_after_func_body. +nl_after_func_body_class = 0 # unsigned number + +# The number of newlines after '}' of a single line function body. Also +# affects class constructors/destructors. +# +# Overrides nl_after_func_body and nl_after_func_body_class. +nl_after_func_body_one_liner = 0 # unsigned number + +# The number of blank lines after a block of variable definitions at the top +# of a function body. +# +# 0: No change (default). +nl_func_var_def_blk = 0 # unsigned number + +# The number of newlines before a block of typedefs. If nl_after_access_spec +# is non-zero, that option takes precedence. +# +# 0: No change (default). +nl_typedef_blk_start = 0 # unsigned number + +# The number of newlines after a block of typedefs. +# +# 0: No change (default). +nl_typedef_blk_end = 0 # unsigned number + +# The maximum number of consecutive newlines within a block of typedefs. +# +# 0: No change (default). +nl_typedef_blk_in = 0 # unsigned number + +# The number of newlines before a block of variable definitions not at the top +# of a function body. If nl_after_access_spec is non-zero, that option takes +# precedence. +# +# 0: No change (default). +nl_var_def_blk_start = 0 # unsigned number + +# The number of newlines after a block of variable definitions not at the top +# of a function body. +# +# 0: No change (default). +nl_var_def_blk_end = 0 # unsigned number + +# The maximum number of consecutive newlines within a block of variable +# definitions. +# +# 0: No change (default). +nl_var_def_blk_in = 0 # unsigned number + +# The minimum number of newlines before a multi-line comment. +# Doesn't apply if after a brace open or another multi-line comment. +nl_before_block_comment = 0 # unsigned number + +# The minimum number of newlines before a single-line C comment. +# Doesn't apply if after a brace open or other single-line C comments. +nl_before_c_comment = 0 # unsigned number + +# The minimum number of newlines before a CPP comment. +# Doesn't apply if after a brace open or other CPP comments. +nl_before_cpp_comment = 0 # unsigned number + +# Whether to force a newline after a multi-line comment. +nl_after_multiline_comment = false # true/false + +# Whether to force a newline after a label's colon. +nl_after_label_colon = false # true/false + +# The number of newlines after '}' or ';' of a struct/enum/union definition. +nl_after_struct = 0 # unsigned number + +# The number of newlines before a class definition. +nl_before_class = 0 # unsigned number + +# The number of newlines after '}' or ';' of a class definition. +nl_after_class = 0 # unsigned number + +# The number of newlines before a namespace. +nl_before_namespace = 0 # unsigned number + +# The number of newlines after '{' of a namespace. This also adds newlines +# before the matching '}'. +# +# 0: Apply eat_blanks_after_open_brace or eat_blanks_before_close_brace if +# applicable, otherwise no change. +# +# Overrides eat_blanks_after_open_brace and eat_blanks_before_close_brace. +nl_inside_namespace = 0 # unsigned number + +# The number of newlines after '}' of a namespace. +nl_after_namespace = 0 # unsigned number + +# The number of newlines before an access specifier label. This also includes +# the Qt-specific 'signals:' and 'slots:'. Will not change the newline count +# if after a brace open. +# +# 0: No change (default). +nl_before_access_spec = 0 # unsigned number + +# The number of newlines after an access specifier label. This also includes +# the Qt-specific 'signals:' and 'slots:'. Will not change the newline count +# if after a brace open. +# +# 0: No change (default). +# +# Overrides nl_typedef_blk_start and nl_var_def_blk_start. +nl_after_access_spec = 0 # unsigned number + +# The number of newlines between a function definition and the function +# comment, as in '// comment\n void foo() {...}'. +# +# 0: No change (default). +nl_comment_func_def = 0 # unsigned number + +# The number of newlines after a try-catch-finally block that isn't followed +# by a brace close. +# +# 0: No change (default). +nl_after_try_catch_finally = 0 # unsigned number + +# (C#) The number of newlines before and after a property, indexer or event +# declaration. +# +# 0: No change (default). +nl_around_cs_property = 0 # unsigned number + +# (C#) The number of newlines between the get/set/add/remove handlers. +# +# 0: No change (default). +nl_between_get_set = 0 # unsigned number + +# (C#) Add or remove newline between property and the '{'. +nl_property_brace = ignore # ignore/add/remove/force + +# Whether to remove blank lines after '{'. +eat_blanks_after_open_brace = false # true/false + +# Whether to remove blank lines before '}'. +eat_blanks_before_close_brace = false # true/false + +# How aggressively to remove extra newlines not in preprocessor. +# +# 0: No change (default) +# 1: Remove most newlines not handled by other config +# 2: Remove all newlines and reformat completely by config +nl_remove_extra_newlines = 0 # unsigned number + +# (Java) Add or remove newline after an annotation statement. Only affects +# annotations that are after a newline. +nl_after_annotation = ignore # ignore/add/remove/force + +# (Java) Add or remove newline between two annotations. +nl_between_annotation = ignore # ignore/add/remove/force + +# The number of newlines before a whole-file #ifdef. +# +# 0: No change (default). +nl_before_whole_file_ifdef = 0 # unsigned number + +# The number of newlines after a whole-file #ifdef. +# +# 0: No change (default). +nl_after_whole_file_ifdef = 0 # unsigned number + +# The number of newlines before a whole-file #endif. +# +# 0: No change (default). +nl_before_whole_file_endif = 0 # unsigned number + +# The number of newlines after a whole-file #endif. +# +# 0: No change (default). +nl_after_whole_file_endif = 0 # unsigned number + +# +# Positioning options +# + +# The position of arithmetic operators in wrapped expressions. +pos_arith = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of assignment in wrapped expressions. Do not affect '=' +# followed by '{'. +pos_assign = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of Boolean operators in wrapped expressions. +pos_bool = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of comparison operators in wrapped expressions. +pos_compare = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of conditional operators, as in the '?' and ':' of +# 'expr ? stmt : stmt', in wrapped expressions. +pos_conditional = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of the comma in wrapped expressions. +pos_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of the comma in enum entries. +pos_enum_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of the comma in the base class list if there is more than one +# line. Affects nl_class_init_args. +pos_class_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of the comma in the constructor initialization list. +# Related to nl_constr_colon, nl_constr_init_args and pos_constr_colon. +pos_constr_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of trailing/leading class colon, between class and base class +# list. Affects nl_class_colon. +pos_class_colon = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# The position of colons between constructor and member initialization. +# Related to nl_constr_colon, nl_constr_init_args and pos_constr_comma. +pos_constr_colon = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# +# Line splitting options +# + +# Try to limit code width to N columns. +code_width = 0 # unsigned number + +# Whether to fully split long 'for' statements at semi-colons. +ls_for_split_full = false # true/false + +# Whether to fully split long function prototypes/calls at commas. +# The option ls_code_width has priority over the option ls_func_split_full. +ls_func_split_full = false # true/false + +# Whether to split lines as close to code_width as possible and ignore some +# groupings. +# The option ls_code_width has priority over the option ls_func_split_full. +ls_code_width = false # true/false + +# +# Code alignment options (not left column spaces/tabs) +# + +# Whether to keep non-indenting tabs. +align_keep_tabs = false # true/false + +# Whether to use tabs for aligning. +align_with_tabs = false # true/false + +# Whether to bump out to the next tab when aligning. +align_on_tabstop = false # true/false + +# Whether to right-align numbers. +align_number_right = false # true/false + +# Whether to keep whitespace not required for alignment. +align_keep_extra_space = false # true/false + +# Whether to align variable definitions in prototypes and functions. +align_func_params = false # true/false + +# The span for aligning parameter definitions in function on parameter name. +# +# 0: Don't align (default). +align_func_params_span = 0 # unsigned number + +# The threshold for aligning function parameter definitions. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_func_params_thresh = 0 # number + +# The gap for aligning function parameter definitions. +align_func_params_gap = 0 # unsigned number + +# The span for aligning constructor value. +# +# 0: Don't align (default). +align_constr_value_span = 0 # unsigned number + +# The threshold for aligning constructor value. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_constr_value_thresh = 0 # number + +# The gap for aligning constructor value. +align_constr_value_gap = 0 # unsigned number + +# Whether to align parameters in single-line functions that have the same +# name. The function names must already be aligned with each other. +align_same_func_call_params = false # true/false + +# The span for aligning function-call parameters for single line functions. +# +# 0: Don't align (default). +align_same_func_call_params_span = 0 # unsigned number + +# The threshold for aligning function-call parameters for single line +# functions. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_same_func_call_params_thresh = 0 # number + +# The span for aligning variable definitions. +# +# 0: Don't align (default). +align_var_def_span = 0 # unsigned number + +# How to consider (or treat) the '*' in the alignment of variable definitions. +# +# 0: Part of the type 'void * foo;' (default) +# 1: Part of the variable 'void *foo;' +# 2: Dangling 'void *foo;' +# Dangling: the '*' will not be taken into account when aligning. +align_var_def_star_style = 0 # unsigned number + +# How to consider (or treat) the '&' in the alignment of variable definitions. +# +# 0: Part of the type 'long & foo;' (default) +# 1: Part of the variable 'long &foo;' +# 2: Dangling 'long &foo;' +# Dangling: the '&' will not be taken into account when aligning. +align_var_def_amp_style = 0 # unsigned number + +# The threshold for aligning variable definitions. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_var_def_thresh = 0 # number + +# The gap for aligning variable definitions. +align_var_def_gap = 0 # unsigned number + +# Whether to align the colon in struct bit fields. +align_var_def_colon = false # true/false + +# The gap for aligning the colon in struct bit fields. +align_var_def_colon_gap = 0 # unsigned number + +# Whether to align any attribute after the variable name. +align_var_def_attribute = false # true/false + +# Whether to align inline struct/enum/union variable definitions. +align_var_def_inline = false # true/false + +# The span for aligning on '=' in assignments. +# +# 0: Don't align (default). +align_assign_span = 0 # unsigned number + +# The span for aligning on '=' in function prototype modifier. +# +# 0: Don't align (default). +align_assign_func_proto_span = 0 # unsigned number + +# The threshold for aligning on '=' in assignments. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_assign_thresh = 0 # number + +# How to apply align_assign_span to function declaration "assignments", i.e. +# 'virtual void foo() = 0' or '~foo() = {default|delete}'. +# +# 0: Align with other assignments (default) +# 1: Align with each other, ignoring regular assignments +# 2: Don't align +align_assign_decl_func = 0 # unsigned number + +# The span for aligning on '=' in enums. +# +# 0: Don't align (default). +align_enum_equ_span = 0 # unsigned number + +# The threshold for aligning on '=' in enums. +# Use a negative number for absolute thresholds. +# +# 0: no limit (default). +align_enum_equ_thresh = 0 # number + +# The span for aligning class member definitions. +# +# 0: Don't align (default). +align_var_class_span = 0 # unsigned number + +# The threshold for aligning class member definitions. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_var_class_thresh = 0 # number + +# The gap for aligning class member definitions. +align_var_class_gap = 0 # unsigned number + +# The span for aligning struct/union member definitions. +# +# 0: Don't align (default). +align_var_struct_span = 0 # unsigned number + +# The threshold for aligning struct/union member definitions. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_var_struct_thresh = 0 # number + +# The gap for aligning struct/union member definitions. +align_var_struct_gap = 0 # unsigned number + +# The span for aligning struct initializer values. +# +# 0: Don't align (default). +align_struct_init_span = 0 # unsigned number + +# The span for aligning single-line typedefs. +# +# 0: Don't align (default). +align_typedef_span = 0 # unsigned number + +# The minimum space between the type and the synonym of a typedef. +align_typedef_gap = 0 # unsigned number + +# How to align typedef'd functions with other typedefs. +# +# 0: Don't mix them at all (default) +# 1: Align the open parenthesis with the types +# 2: Align the function type name with the other type names +align_typedef_func = 0 # unsigned number + +# How to consider (or treat) the '*' in the alignment of typedefs. +# +# 0: Part of the typedef type, 'typedef int * pint;' (default) +# 1: Part of type name: 'typedef int *pint;' +# 2: Dangling: 'typedef int *pint;' +# Dangling: the '*' will not be taken into account when aligning. +align_typedef_star_style = 0 # unsigned number + +# How to consider (or treat) the '&' in the alignment of typedefs. +# +# 0: Part of the typedef type, 'typedef int & intref;' (default) +# 1: Part of type name: 'typedef int &intref;' +# 2: Dangling: 'typedef int &intref;' +# Dangling: the '&' will not be taken into account when aligning. +align_typedef_amp_style = 0 # unsigned number + +# The span for aligning comments that end lines. +# +# 0: Don't align (default). +align_right_cmt_span = 0 # unsigned number + +# Minimum number of columns between preceding text and a trailing comment in +# order for the comment to qualify for being aligned. Must be non-zero to have +# an effect. +align_right_cmt_gap = 0 # unsigned number + +# If aligning comments, whether to mix with comments after '}' and #endif with +# less than three spaces before the comment. +align_right_cmt_mix = false # true/false + +# Whether to only align trailing comments that are at the same brace level. +align_right_cmt_same_level = false # true/false + +# Minimum column at which to align trailing comments. Comments which are +# aligned beyond this column, but which can be aligned in a lesser column, +# may be "pulled in". +# +# 0: Ignore (default). +align_right_cmt_at_col = 0 # unsigned number + +# The span for aligning function prototypes. +# +# 0: Don't align (default). +align_func_proto_span = 0 # unsigned number + +# The threshold for aligning function prototypes. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_func_proto_thresh = 0 # number + +# Minimum gap between the return type and the function name. +align_func_proto_gap = 0 # unsigned number + +# Whether to align function prototypes on the 'operator' keyword instead of +# what follows. +align_on_operator = false # true/false + +# Whether to mix aligning prototype and variable declarations. If true, +# align_var_def_XXX options are used instead of align_func_proto_XXX options. +align_mix_var_proto = false # true/false + +# Whether to align single-line functions with function prototypes. +# Uses align_func_proto_span. +align_single_line_func = false # true/false + +# Whether to align the open brace of single-line functions. +# Requires align_single_line_func=true. Uses align_func_proto_span. +align_single_line_brace = false # true/false + +# Gap for align_single_line_brace. +align_single_line_brace_gap = 0 # unsigned number + +# (OC) The span for aligning Objective-C message specifications. +# +# 0: Don't align (default). +align_oc_msg_spec_span = 0 # unsigned number + +# Whether to align macros wrapped with a backslash and a newline. This will +# not work right if the macro contains a multi-line comment. +align_nl_cont = false # true/false + +# Whether to align macro functions and variables together. +align_pp_define_together = false # true/false + +# The span for aligning on '#define' bodies. +# +# =0: Don't align (default) +# >0: Number of lines (including comments) between blocks +align_pp_define_span = 0 # unsigned number + +# The minimum space between label and value of a preprocessor define. +align_pp_define_gap = 0 # unsigned number + +# Whether to align lines that start with '<<' with previous '<<'. +# +# Default: true +align_left_shift = true # true/false + +# Whether to align text after 'asm volatile ()' colons. +align_asm_colon = false # true/false + +# (OC) Span for aligning parameters in an Objective-C message call +# on the ':'. +# +# 0: Don't align. +align_oc_msg_colon_span = 0 # unsigned number + +# (OC) Whether to always align with the first parameter, even if it is too +# short. +align_oc_msg_colon_first = false # true/false + +# (OC) Whether to align parameters in an Objective-C '+' or '-' declaration +# on the ':'. +align_oc_decl_colon = false # true/false + +# (OC) Whether to not align parameters in an Objectve-C message call if first +# colon is not on next line of the message call (the same way Xcode does +# aligment) +align_oc_msg_colon_xcode_like = false # true/false + +# +# Comment modification options +# + +# Try to wrap comments at N columns. +cmt_width = 0 # unsigned number + +# How to reflow comments. +# +# 0: No reflowing (apart from the line wrapping due to cmt_width) (default) +# 1: No touching at all +# 2: Full reflow +cmt_reflow_mode = 1 # unsigned number + +# Whether to convert all tabs to spaces in comments. If false, tabs in +# comments are left alone, unless used for indenting. +cmt_convert_tab_to_spaces = false # true/false + +# Whether to apply changes to multi-line comments, including cmt_width, +# keyword substitution and leading chars. +# +# Default: true +cmt_indent_multi = false # true/false + +# Whether to group c-comments that look like they are in a block. +cmt_c_group = false # true/false + +# Whether to put an empty '/*' on the first line of the combined c-comment. +cmt_c_nl_start = false # true/false + +# Whether to add a newline before the closing '*/' of the combined c-comment. +cmt_c_nl_end = false # true/false + +# Whether to change cpp-comments into c-comments. +cmt_cpp_to_c = false # true/false + +# Whether to group cpp-comments that look like they are in a block. Only +# meaningful if cmt_cpp_to_c=true. +cmt_cpp_group = false # true/false + +# Whether to put an empty '/*' on the first line of the combined cpp-comment +# when converting to a c-comment. +# +# Requires cmt_cpp_to_c=true and cmt_cpp_group=true. +cmt_cpp_nl_start = false # true/false + +# Whether to add a newline before the closing '*/' of the combined cpp-comment +# when converting to a c-comment. +# +# Requires cmt_cpp_to_c=true and cmt_cpp_group=true. +cmt_cpp_nl_end = false # true/false + +# Whether to put a star on subsequent comment lines. +cmt_star_cont = false # true/false + +# The number of spaces to insert at the start of subsequent comment lines. +cmt_sp_before_star_cont = 0 # unsigned number + +# The number of spaces to insert after the star on subsequent comment lines. +cmt_sp_after_star_cont = 0 # unsigned number + +# For multi-line comments with a '*' lead, remove leading spaces if the first +# and last lines of the comment are the same length. +# +# Default: true +cmt_multi_check_last = true # true/false + +# For multi-line comments with a '*' lead, remove leading spaces if the first +# and last lines of the comment are the same length AND if the length is +# bigger as the first_len minimum. +# +# Default: 4 +cmt_multi_first_len_minimum = 4 # unsigned number + +# Path to a file that contains text to insert at the beginning of a file if +# the file doesn't start with a C/C++ comment. If the inserted text contains +# '$(filename)', that will be replaced with the current file's name. +cmt_insert_file_header = "" # string + +# Path to a file that contains text to insert at the end of a file if the +# file doesn't end with a C/C++ comment. If the inserted text contains +# '$(filename)', that will be replaced with the current file's name. +cmt_insert_file_footer = "" # string + +# Path to a file that contains text to insert before a function definition if +# the function isn't preceded by a C/C++ comment. If the inserted text +# contains '$(function)', '$(javaparam)' or '$(fclass)', these will be +# replaced with, respectively, the name of the function, the javadoc '@param' +# and '@return' stuff, or the name of the class to which the member function +# belongs. +cmt_insert_func_header = "" # string + +# Path to a file that contains text to insert before a class if the class +# isn't preceded by a C/C++ comment. If the inserted text contains '$(class)', +# that will be replaced with the class name. +cmt_insert_class_header = "" # string + +# Path to a file that contains text to insert before an Objective-C message +# specification, if the method isn't preceded by a C/C++ comment. If the +# inserted text contains '$(message)' or '$(javaparam)', these will be +# replaced with, respectively, the name of the function, or the javadoc +# '@param' and '@return' stuff. +cmt_insert_oc_msg_header = "" # string + +# Whether a comment should be inserted if a preprocessor is encountered when +# stepping backwards from a function name. +# +# Applies to cmt_insert_oc_msg_header, cmt_insert_func_header and +# cmt_insert_class_header. +cmt_insert_before_preproc = false # true/false + +# Whether a comment should be inserted if a function is declared inline to a +# class definition. +# +# Applies to cmt_insert_func_header. +# +# Default: true +cmt_insert_before_inlines = true # true/false + +# Whether a comment should be inserted if the function is a class constructor +# or destructor. +# +# Applies to cmt_insert_func_header. +cmt_insert_before_ctor_dtor = false # true/false + +# +# Code modifying options (non-whitespace) +# + +# Add or remove braces on a single-line 'do' statement. +mod_full_brace_do = force # ignore/add/remove/force + +# Add or remove braces on a single-line 'for' statement. +mod_full_brace_for = force # ignore/add/remove/force + +# (Pawn) Add or remove braces on a single-line function definition. +mod_full_brace_function = force # ignore/add/remove/force + +# Add or remove braces on a single-line 'if' statement. Braces will not be +# removed if the braced statement contains an 'else'. +mod_full_brace_if = force # ignore/add/remove/force + +# Whether to enforce that all blocks of an 'if'/'else if'/'else' chain either +# have, or do not have, braces. If true, braces will be added if any block +# needs braces, and will only be removed if they can be removed from all +# blocks. +# +# Overrides mod_full_brace_if. +mod_full_brace_if_chain = false # true/false + +# Whether to add braces to all blocks of an 'if'/'else if'/'else' chain. +# If true, mod_full_brace_if_chain will only remove braces from an 'if' that +# does not have an 'else if' or 'else'. +mod_full_brace_if_chain_only = false # true/false + +# Add or remove braces on single-line 'while' statement. +mod_full_brace_while = force # ignore/add/remove/force + +# Add or remove braces on single-line 'using ()' statement. +mod_full_brace_using = ignore # ignore/add/remove/force + +# Don't remove braces around statements that span N newlines +mod_full_brace_nl = 0 # unsigned number + +# Whether to prevent removal of braces from 'if'/'for'/'while'/etc. blocks +# which span multiple lines. +# +# Affects: +# mod_full_brace_for +# mod_full_brace_if +# mod_full_brace_if_chain +# mod_full_brace_if_chain_only +# mod_full_brace_while +# mod_full_brace_using +# +# Does not affect: +# mod_full_brace_do +# mod_full_brace_function +mod_full_brace_nl_block_rem_mlcond = false # true/false + +# Add or remove unnecessary parenthesis on 'return' statement. +mod_paren_on_return = remove # ignore/add/remove/force + +# (Pawn) Whether to change optional semicolons to real semicolons. +mod_pawn_semicolon = false # true/false + +# Whether to fully parenthesize Boolean expressions in 'while' and 'if' +# statement, as in 'if (a && b > c)' => 'if (a && (b > c))'. +mod_full_paren_if_bool = false # true/false + +# Whether to remove superfluous semicolons. +mod_remove_extra_semicolon = false # true/false + +# If a function body exceeds the specified number of newlines and doesn't have +# a comment after the close brace, a comment will be added. +mod_add_long_function_closebrace_comment = 0 # unsigned number + +# If a namespace body exceeds the specified number of newlines and doesn't +# have a comment after the close brace, a comment will be added. +mod_add_long_namespace_closebrace_comment = 0 # unsigned number + +# If a class body exceeds the specified number of newlines and doesn't have a +# comment after the close brace, a comment will be added. +mod_add_long_class_closebrace_comment = 0 # unsigned number + +# If a switch body exceeds the specified number of newlines and doesn't have a +# comment after the close brace, a comment will be added. +mod_add_long_switch_closebrace_comment = 0 # unsigned number + +# If an #ifdef body exceeds the specified number of newlines and doesn't have +# a comment after the #endif, a comment will be added. +mod_add_long_ifdef_endif_comment = 0 # unsigned number + +# If an #ifdef or #else body exceeds the specified number of newlines and +# doesn't have a comment after the #else, a comment will be added. +mod_add_long_ifdef_else_comment = 0 # unsigned number + +# Whether to take care of the case by the mod_sort_xx options. +mod_sort_case_sensitive = false # true/false + +# Whether to sort consecutive single-line 'import' statements. +mod_sort_import = false # true/false + +# (C#) Whether to sort consecutive single-line 'using' statements. +mod_sort_using = false # true/false + +# Whether to sort consecutive single-line '#include' statements (C/C++) and +# '#import' statements (Objective-C). Be aware that this has the potential to +# break your code if your includes/imports have ordering dependencies. +mod_sort_include = false # true/false + +# Whether to prioritize '#include' and '#import' statements that contain +# filename without extension when sorting is enabled. +mod_sort_incl_import_prioritize_filename = false # true/false + +# Whether to prioritize '#include' and '#import' statements that does not +# contain extensions when sorting is enabled. +mod_sort_incl_import_prioritize_extensionless = false # true/false + +# Whether to prioritize '#include' and '#import' statements that contain +# angle over quotes when sorting is enabled. +mod_sort_incl_import_prioritize_angle_over_quotes = false # true/false + +# Whether to ignore file extension in '#include' and '#import' statements +# for sorting comparison. +mod_sort_incl_import_ignore_extension = false # true/false + +# Whether to group '#include' and '#import' statements when sorting is enabled. +mod_sort_incl_import_grouping_enabled = false # true/false + +# Whether to move a 'break' that appears after a fully braced 'case' before +# the close brace, as in 'case X: { ... } break;' => 'case X: { ... break; }'. +mod_move_case_break = false # true/false + +# Add or remove braces around a fully braced case statement. Will only remove +# braces if there are no variable declarations in the block. +mod_case_brace = ignore # ignore/add/remove/force + +# Whether to remove a void 'return;' that appears as the last statement in a +# function. +mod_remove_empty_return = false # true/false + +# Add or remove the comma after the last value of an enumeration. +mod_enum_last_comma = ignore # ignore/add/remove/force + +# (OC) Whether to organize the properties. If true, properties will be +# rearranged according to the mod_sort_oc_property_*_weight factors. +mod_sort_oc_properties = false # true/false + +# (OC) Weight of a class property modifier. +mod_sort_oc_property_class_weight = 0 # number + +# (OC) Weight of 'atomic' and 'nonatomic'. +mod_sort_oc_property_thread_safe_weight = 0 # number + +# (OC) Weight of 'readwrite' when organizing properties. +mod_sort_oc_property_readwrite_weight = 0 # number + +# (OC) Weight of a reference type specifier ('retain', 'copy', 'assign', +# 'weak', 'strong') when organizing properties. +mod_sort_oc_property_reference_weight = 0 # number + +# (OC) Weight of getter type ('getter=') when organizing properties. +mod_sort_oc_property_getter_weight = 0 # number + +# (OC) Weight of setter type ('setter=') when organizing properties. +mod_sort_oc_property_setter_weight = 0 # number + +# (OC) Weight of nullability type ('nullable', 'nonnull', 'null_unspecified', +# 'null_resettable') when organizing properties. +mod_sort_oc_property_nullability_weight = 0 # number + +# +# Preprocessor options +# + +# Add or remove indentation of preprocessor directives inside #if blocks +# at brace level 0 (file-level). +pp_indent = ignore # ignore/add/remove/force + +# Whether to indent #if/#else/#endif at the brace level. If false, these are +# indented from column 1. +pp_indent_at_level = true # true/false + +# Specifies the number of columns to indent preprocessors per level +# at brace level 0 (file-level). If pp_indent_at_level=false, also specifies +# the number of columns to indent preprocessors per level +# at brace level > 0 (function-level). +# +# Default: 1 +pp_indent_count = 1 # unsigned number + +# Add or remove space after # based on pp_level of #if blocks. +pp_space = remove # ignore/add/remove/force + +# Sets the number of spaces per level added with pp_space. +pp_space_count = 0 # unsigned number + +# The indent for '#region' and '#endregion' in C# and '#pragma region' in +# C/C++. Negative values decrease indent down to the first column. +pp_indent_region = 0 # number + +# Whether to indent the code between #region and #endregion. +pp_region_indent_code = false # true/false + +# If pp_indent_at_level=true, sets the indent for #if, #else and #endif when +# not at file-level. Negative values decrease indent down to the first column. +# +# =0: Indent preprocessors using output_tab_size +# >0: Column at which all preprocessors will be indented +pp_indent_if = 0 # number + +# Whether to indent the code between #if, #else and #endif. +pp_if_indent_code = false # true/false + +# Whether to indent '#define' at the brace level. If false, these are +# indented from column 1. +pp_define_at_level = false # true/false + +# Whether to ignore the '#define' body while formatting. +pp_ignore_define_body = false # true/false + +# Whether to indent case statements between #if, #else, and #endif. +# Only applies to the indent of the preprocesser that the case statements +# directly inside of. +# +# Default: true +pp_indent_case = true # true/false + +# Whether to indent whole function definitions between #if, #else, and #endif. +# Only applies to the indent of the preprocesser that the function definition +# is directly inside of. +# +# Default: true +pp_indent_func_def = true # true/false + +# Whether to indent extern C blocks between #if, #else, and #endif. +# Only applies to the indent of the preprocesser that the extern block is +# directly inside of. +# +# Default: true +pp_indent_extern = true # true/false + +# Whether to indent braces directly inside #if, #else, and #endif. +# Only applies to the indent of the preprocesser that the braces are directly +# inside of. +# +# Default: true +pp_indent_brace = true # true/false + +# +# Sort includes options +# + +# The regex for include category with priority 0. +include_category_0 = "" # string + +# The regex for include category with priority 1. +include_category_1 = "" # string + +# The regex for include category with priority 2. +include_category_2 = "" # string + +# +# Use or Do not Use options +# + +# true: indent_func_call_param will be used (default) +# false: indent_func_call_param will NOT be used +# +# Default: true +use_indent_func_call_param = true # true/false + +# The value of the indentation for a continuation line is calculated +# differently if the statement is: +# - a declaration: your case with QString fileName ... +# - an assignment: your case with pSettings = new QSettings( ... +# +# At the second case the indentation value might be used twice: +# - at the assignment +# - at the function call (if present) +# +# To prevent the double use of the indentation value, use this option with the +# value 'true'. +# +# true: indent_continue will be used only once +# false: indent_continue will be used every time (default) +use_indent_continue_only_once = false # true/false + +# The value might be used twice: +# - at the assignment +# - at the opening brace +# +# To prevent the double use of the indentation value, use this option with the +# value 'true'. +# +# true: indentation will be used only once +# false: indentation will be used every time (default) +indent_cpp_lambda_only_once = false # true/false + +# Whether sp_after_angle takes precedence over sp_inside_fparen. This was the +# historic behavior, but is probably not the desired behavior, so this is off +# by default. +use_sp_after_angle_always = false # true/false + +# Whether to apply special formatting for Qt SIGNAL/SLOT macros. Essentially, +# this tries to format these so that they match Qt's normalized form (i.e. the +# result of QMetaObject::normalizedSignature), which can slightly improve the +# performance of the QObject::connect call, rather than how they would +# otherwise be formatted. +# +# See options_for_QT.cpp for details. +# +# Default: true +use_options_overriding_for_qt_macros = true # true/false + +# If true: the form feed character is removed from the list +# of whitespace characters. +# See https://en.cppreference.com/w/cpp/string/byte/isspace +use_form_feed_no_more_as_whitespace_character = false # true/false + +# +# Warn levels - 1: error, 2: warning (default), 3: note +# + +# (C#) Warning is given if doing tab-to-\t replacement and we have found one +# in a C# verbatim string literal. +# +# Default: 2 +warn_level_tabs_found_in_verbatim_string_literals = 2 # unsigned number + +# Limit the number of loops. +# Used by uncrustify.cpp to exit from infinite loop. +# 0: no limit. +debug_max_number_of_loops = 0 # number + +# Set the number of the line to protocol; +# Used in the function prot_the_line if the 2. parameter is zero. +# 0: nothing protocol. +debug_line_number_to_protocol = 0 # number + +# Meaning of the settings: +# Ignore - do not do any changes +# Add - makes sure there is 1 or more space/brace/newline/etc +# Force - makes sure there is exactly 1 space/brace/newline/etc, +# behaves like Add in some contexts +# Remove - removes space/brace/newline/etc +# +# +# - Token(s) can be treated as specific type(s) with the 'set' option: +# `set tokenType tokenString [tokenString...]` +# +# Example: +# `set BOOL __AND__ __OR__` +# +# tokenTypes are defined in src/token_enum.h, use them without the +# 'CT_' prefix: 'CT_BOOL' => 'BOOL' +# +# +# - Token(s) can be treated as type(s) with the 'type' option. +# `type tokenString [tokenString...]` +# +# Example: +# `type int c_uint_8 Rectangle` +# +# This can also be achieved with `set TYPE int c_uint_8 Rectangle` +# +# +# To embed whitespace in tokenStrings use the '\' escape character, or quote +# the tokenStrings. These quotes are supported: "'` +# +# +# - Support for the auto detection of languages through the file ending can be +# added using the 'file_ext' command. +# `file_ext langType langString [langString..]` +# +# Example: +# `file_ext CPP .ch .cxx .cpp.in` +# +# langTypes are defined in uncrusify_types.h in the lang_flag_e enum, use +# them without the 'LANG_' prefix: 'LANG_CPP' => 'CPP' +# +# +# - Custom macro-based indentation can be set up using 'macro-open', +# 'macro-else' and 'macro-close'. +# `(macro-open | macro-else | macro-close) tokenString` +# +# Example: +# `macro-open BEGIN_TEMPLATE_MESSAGE_MAP` +# `macro-open BEGIN_MESSAGE_MAP` +# `macro-close END_MESSAGE_MAP` +# +# +# option(s) with 'not default' value: 67 +# + +# Custom types for MicroPython +type uint qstr diff --git a/tools/upip.py b/tools/upip.py index 27fbae272ff62..a7187e700d7c0 100644 --- a/tools/upip.py +++ b/tools/upip.py @@ -12,6 +12,7 @@ import ujson as json import uzlib import upip_utarfile as tarfile + gc.collect() @@ -22,9 +23,11 @@ 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 44d6364524294..3e527fad8da17 100644 --- a/tools/upip_utarfile.py +++ b/tools/upip_utarfile.py @@ -13,11 +13,12 @@ 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 @@ def readinto(self, buf): 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 @@ def skip(self): 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 @@ def __init__(self, name=None, fileobj=None): self.subf = None def next(self): - 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) - - # 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 + 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) + + # 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 def __iter__(self): return self diff --git a/tools/usb_descriptor b/tools/usb_descriptor index 701cafc50e2e5..2eaa6114b209f 160000 --- a/tools/usb_descriptor +++ b/tools/usb_descriptor @@ -1 +1 @@ -Subproject commit 701cafc50e2e574dccaf7a340eedbd64a0b41a42 +Subproject commit 2eaa6114b209fe7f0a795eda8d6a7b3b93d76d2e